Custom Hooks
Extract and reuse stateful logic by writing your own hooks — the height of clean React.
What you will learn
- Write a custom hook
- Reuse logic across components
- Follow the hook rules
Your own reusable logic
A custom hook is just a function whose name starts with use and that calls other hooks. It lets you package up logic (like fetching, or a toggle) and reuse it anywhere.
// Custom hook: a reusable on/off toggle
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn(o => !o);
return [on, toggle];
}
function App() {
const [visible, toggleVisible] = useToggle(false);
return (
<div>
<button onClick={toggleVisible}>{visible ? "Hide" : "Show"}</button>
{visible && <p>Now you see me! 👀</p>}
</div>
);
}A custom hook is just a normal function (name starting with use) that uses other hooks inside it. useToggle keeps a boolean in useState and bundles a toggle function that flips it, then return [on, toggle] — exactly the shape useState returns. Now App writes one line, const [visible, toggleVisible] = useToggle(false), and gets ready-made on/off logic. You could reuse useToggle in any component, so the toggle logic is written once and shared.
Note: Output:
A button reading Show. Click it and the line “Now you see me! 👀” appears and the button changes to Hide. Click again to hide it. All driven by the reusable useToggle hook.
Note: Rules of hooks: only call hooks at the top level of a component or custom hook (not inside loops or conditions), and only from React functions. Custom hooks compose perfectly because they follow the same rules.
Tip: A classic custom hook is useFetch(url) — wrap the loading/error/data fetching logic once, then reuse it on every screen that loads data.
Q. What must a custom hook’s name start with?
✍️ Practice
- Write a
useTogglehook and use it to show/hide an element. - Write a
useCounterhook with increment and reset.
🏠 Homework
- Write a
useFetch(url)custom hook that returns { data, loading } and use it.