1. Why Create Custom Hooks?
In React, components reuse UI structures. But when you need to reuse stateful logic (such as window resizing, local storage synchronization, or API fetching) across multiple unrelated components, you extract that logic into a Custom Hook.
2. Rules for Custom Hooks
- A custom hook is a JavaScript function whose name must begin with
use(e.g.useLocalStorage,useFetch,useOnlineStatus). - Custom hooks can call other React hooks (like
useState,useEffect).
3. Creating a useLocalStorage Custom Hook
import { useState, useEffect } from 'react';
export function useLocalStorage(key, initialValue) {
// Read existing value from localStorage on first render
const [storedValue, setStoredValue] = useState(() => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error("Error reading localStorage key:", key, error);
return initialValue;
}
});
// Automatically write to localStorage whenever storedValue changes
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error("Error writing to localStorage:", error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
4. Using Your Custom Hook in Components
import { useLocalStorage } from './useLocalStorage';
function ExamThemeSelector() {
// Seamlessly stays in sync with browser localStorage!
const [theme, setTheme] = useLocalStorage("cbt_theme", "light");
return (
);
}