Creating and Using Custom Hooks
A custom hook is a JavaScript function whose name starts with use and which calls other hooks such as useState or useEffect. It lets you pull stateful logic out of a component and reuse it in other components, while each component still gets its own independent state. Typical candidates are tracking window size, syncing a value with localStorage, debouncing input or toggling a boolean.
Spotting logic worth extracting
The signal is duplication. If two components both declare a piece of state, set up the same effect and clean it up the same way, that block can move into a hook. The component then reads like a description of what it needs, and the details live in one tested place.
Building a useLocalStorage hook
This hook behaves like useState but remembers the value between visits.
import { useEffect, useState } from 'react';
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// storage may be full or blocked; ignore
}
}, [key, value]);
return [value, setValue];
}
The lazy initialiser, the function passed to useState, reads storage only on the first render instead of on every render. The try...catch blocks matter because storage can be unavailable in private windows.
Using the hook in components
import { useLocalStorage } from './useLocalStorage';
function ThemeToggle() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Theme: {theme}
</button>
);
}
function NotesBox() {
const [note, setNote] = useLocalStorage('draft-note', '');
return <textarea value={note} onChange={(e) => setNote(e.target.value)} />;
}
Both components call the same hook, yet their state is separate. A custom hook shares logic, not data. If you need the same data in several places, combine the hook with context or lift the state up.
Deciding what the hook returns
Return whatever is easiest for callers. An array, like [value, setValue], lets each component name the items freely, which suits hooks with two outputs. An object, like { data, error, loading }, is clearer when there are several values, because callers pick fields by name and order does not matter.
Hooks can also accept options. A useDebounce(value, delay) hook, for example, takes the delay as a second argument so each caller can tune it.
Rules and mistakes to watch
Custom hooks follow the same rules as built-in ones. Call them only at the top level of a component or another hook, never inside conditions, loops or event handlers, because React relies on hooks being called in the same order on every render. The use prefix is what lets the linter check this, so do not drop it.
A subtle mistake is returning a new object or function on every render and then using it as an effect dependency elsewhere. The effect re-runs every time. Wrap returned functions in useCallback or memoise returned objects with useMemo when callers might depend on them.
The reverse mistake is turning every helper into a hook. A function that does not call any hooks, like formatting a date, should be a plain function without the use name.
Checklist for a good custom hook
- Name starts with
useand describes the behaviour. - It calls at least one other hook.
- Effects clean up after themselves.
- Return values are stable when callers may depend on them.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.