Custom hooks are functions starting with use that call other hooks inside. They let multiple components share stateful logic without duplicating code. Each component that calls the hook gets its own independent state.
Custom Hooks
// useLocalStorage hook
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initial;
});
const set = (v) => {
setValue(v);
localStorage.setItem(key, JSON.stringify(v));
};
return [value, set];
}
// Usage
const [theme, setTheme] = useLocalStorage("theme", "light");