Custom hooks
Extracting reusable stateful logic into your own hook, the use-prefix convention, and composing built-in hooks inside one, with a worked example.
The rules of hooksuseEffect and synchronizing with external systemsuseRef and mutable values
Custom hooks
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A custom hook is just a regular function that calls one or more built-in hooks and whose name starts with use — there is no separate API for defining one.
- The use prefix is not cosmetic: the rules-of-hooks linter uses that exact naming convention to decide which functions it should check for violations, so an unprefixed function that calls hooks is not linted and can silently break those rules.
- A custom hook can call useState, useEffect, useRef, or any other hook internally, and compose several of them into one reusable unit of behavior.
- Extracting logic into a custom hook shares behavior between components without adding any extra component to the render tree, unlike a render prop or a higher-order component.
- Each component that calls a custom hook gets its own independent state — calling useToggle() in two components does not share one boolean between them.
- A custom hook returning a stable array or object shape, similar to useState's [value, setValue] tuple, makes it easy for callers to rename what they destructure.
Spotting logic worth extracting
Stateful logic starts to feel worth extracting the moment you write the same useState plus useEffect combination in a second component. A toggle for a boolean flag is a good first example, since it shows up constantly: sidebars, modals, dropdowns, checkboxes.
Written inline, a toggle looks like this in every component that needs one:
function Sidebar() {
const [isOpen, setIsOpen] = useState(false);
function toggle() {
setIsOpen((previous) => !previous);
}
// ...
}
Copy that into a second component and a third, and now three places need to stay in sync if the toggling logic ever changes — say, to also close the sidebar when a different one opens.
Extracting a custom hook
The fix is to pull the state and the function that updates it into their own function, named with a use prefix:
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
function toggle() {
setValue((previous) => !previous);
}
return [value, toggle];
}
Any component can now call it the same way it would call useState:
function Sidebar() {
const [isOpen, toggleOpen] = useToggle(false);
return (
<div>
<button onClick={toggleOpen}>{isOpen ? "Close" : "Open"} sidebar</button>
{isOpen && <nav>...</nav>}
</div>
);
}
useToggle is nothing more than a function that calls useState and returns a tuple shaped like useState’s own [value, setter] return value — that mirrored shape is a convention, not a requirement, chosen to make useToggle feel familiar to anyone who already knows useState.
Composing several built-in hooks into one
Custom hooks get more useful once they combine more than one built-in hook. A hook that reads from and writes to localStorage, keeping state in sync with it, needs useState for the in-memory value, useEffect to persist it, and benefits from useRef to avoid re-reading localStorage on every render:
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = window.localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
A component uses it exactly like useState, but the value now survives a page reload:
function NotesEditor() {
const [draft, setDraft] = useLocalStorage("draft-note", "");
return (
<textarea value={draft} onChange={(event) => setDraft(event.target.value)} />
);
}
All the mechanics — reading initial state lazily, writing an effect that runs after state changes, returning a useState-shaped tuple — are ordinary hook rules applied inside one function. Nothing about useLocalStorage is special-cased by React; it works because it’s built entirely from hooks React already knows how to run in order, on every render, for the component that calls it.
Why the naming convention isn’t optional in practice
It’s tempting to think of the use prefix as a style preference, but the React ESLint plugin’s rules-of-hooks check specifically looks for that prefix to decide which functions to apply its checks to. A function named getToggleState that internally calls useState conditionally — which breaks the rules of hooks — would not be flagged, because the linter has no way to know it’s a hook-calling function at all. Name it useToggleState, and the same conditional call gets caught immediately. The convention is how the tooling, not just other developers, recognizes a hook.
Independent state per call
A common surprise for newcomers: calling useToggle() in two separate components does not link them. Each call runs its own independent useState under the hood, scoped to the component instance that called it, exactly as if each component had written out the useState and toggle function itself. Sharing state across components is a separate problem, solved by lifting state up or by context, both covered earlier in this roadmap.
What the video covers
Web Dev Simplified’s Learn Custom Hooks In 10 Minutes walks through extracting a useState and useEffect combination into a reusable, use-prefixed hook, which is the same core move behind both useToggle and useLocalStorage above. It is a focused, single-example video; composing three or more built-in hooks into one custom hook, and the linting reason the naming convention matters, get more space in this lesson than in the video itself.
Where this fits
Custom hooks package reusable logic. The next lesson looks at a related but distinct design question: who owns a component’s state at all — the component itself, or whoever renders it. Next: controlled vs. uncontrolled components.
Check yourself
What, mechanically, makes a function a custom hook rather than just a helper function?
Nothing beyond convention and the fact that it calls other hooks internally. A custom hook is a normal JavaScript function, named with a use prefix, that calls built-in hooks like useState or useEffect inside it.
Why does the use prefix matter beyond readability?
The ESLint rules-of-hooks plugin relies on that exact naming pattern to know which functions to check for rule violations, such as calling a hook conditionally. A function that calls hooks but is not named with a use prefix will not be checked, so violations inside it go undetected.
If two different components both call the same custom hook, do they share state?
No. Each call to a custom hook gets its own independent state, because the hooks inside it (such as useState) run separately for each component that calls the hook, the same way two components each calling useState independently never share a value.
What is a concrete benefit of extracting logic into a custom hook instead of a higher-order component?
The custom hook adds no wrapper component to the rendered tree and introduces no risk of colliding injected prop names, since it simply returns a value the calling component destructures itself.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.