Sub topic 5
Custom hooks for reusable logic
This chapter assumes you know function components, useState and useEffect, and event handlers. It shows how to pull stateful logic out of a component so several components can reuse it.
What a custom hook is
A custom hook is a JavaScript function whose name starts with use and that calls other hooks. It is not a component and it returns no JSX. It returns whatever the caller needs: values, functions, or both.
Before hooks, sharing stateful logic meant render props or higher-order components, both of which add wrapper components to the tree. A custom hook shares the logic without adding anything to the tree.
A first example
This hook owns a boolean and the functions that change it.
import { useCallback, useState } from 'react';
export function useToggle(initialOn = false) {
const [on, setOn] = useState(initialOn);
const toggle = useCallback(() => setOn((prev) => !prev), []);
const reset = useCallback(() => setOn(initialOn), [initialOn]);
return { on, toggle, reset };
}
export function Menu() {
const { on, toggle } = useToggle();
return (
<div>
<button onClick={toggle}>{on ? 'Close' : 'Open'} menu</button>
{on && (
<ul>
<li>Home</li>
<li>Settings</li>
</ul>
)}
</div>
);
}Menu decides the markup. useToggle decides how the state changes. Any other component, such as a modal or an accordion item, can call useToggle and render something different.
How state is shared
Calling a hook reuses the logic, not the state. Each call creates new state that belongs to the component that made the call. If two components must see the same value, lift the state to a common parent or share it through context. Both are covered in other chapters.
Rules and common errors
- Name the hook with
use. Linting tools rely on the prefix to enforce the rules of hooks. Without it, mistakes go unflagged. - Call hooks at the top level. Do not call them inside conditions, loops, or nested functions. React matches hook calls by their order on every render.
- Keep returned functions stable. Wrap them in
useCallbackif consumers pass them to memoized children or list them in effect dependencies. Otherwise each render returns new function identities and effects may re-run. - Do not hide too much. A hook that takes ten options to cover every case is hard to use. The patterns later in this tutorial, prop getters and the state reducer, give consumers control without more options.
Why this matters for later patterns
Hooks are the base for the later patterns in this tutorial. Prop getters wrap a hook's handlers into ready-to-spread props. The state reducer pattern lets callers change how a hook updates its state. Headless components combine both, so the hook holds all the logic and the consumer supplies all the UI.
Exercise
Two components, Menu and Modal, each call useToggle(). When the user opens the menu, does the modal open too? Why or why not?
Show answer
No. Each call to useToggle runs its own useState, so each component has separate state. The hook shares the logic, not the values. To open both together, lift the state into a common parent and pass it down, or share it through context.