Custom Hooks and Reusable Logic
Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.
What you will be able to do
#- Extract reusable stateful logic into a custom hook.
- Explain that hooks share logic, not state.
- Apply the rules of hooks inside a custom hook.
Overview
#Hooks share logic, not state
A custom hook is a function whose name starts with use that calls other hooks. It lets you reuse stateful logic between components. Each call to the hook creates its own independent state; the hook shares logic, not state.
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((v) => !v), []);
return [on, toggle] as const;
}
Two components that call useToggle each get their own boolean. To share the same state, lift it or put it in context.
The rules still apply
Hooks must be called at the top level of a component or another hook, never inside conditions, loops or nested functions. A custom hook is just a function, so it must follow the same rules.
// wrong: conditional hook call
if (enabled) { const [x, setX] = useState(0); }
One hook per concern
A hook that fetches, formats and manages a form is hard to reuse and test. Split it into small hooks and compose them.
const user = useUser(id);
const name = useFormattedName(user);
Returning a stable API
Return a tuple for two values and an object for several. Memoize callbacks you return so consumers can use them as dependencies.
Testing a hook
Test a hook through a small component that uses it, or with a hook testing helper that renders it in isolation. Assert the values and the callbacks it returns.
Pitfall: hiding shared state in a hook
If two components call a hook that reads a module-level variable, they share that variable, which is easy to miss. Keep hook state inside the hook unless sharing is intentional and documented.
Pitfall: extracting too early
Do not create a hook for one use. Extract when the same logic appears in two places and the abstraction is clear.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Two components call useToggle. Do they share the boolean?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.tsxfunction useToggle() { const [on, setOn] = useState(false); return [on, () => setOn((v) => !v)] as const; }Exercise 2Implement
Implement a useLocalStorage hook that reads and writes a string value, hydration-safe.
starter.tsxexport function useLocalStorage(key: string, initial: string) { return [initial, () => {}] as const; }Reveal the reference answer
reference.tsximport { useEffect, useState } from 'react'; export function useLocalStorage(key: string, initial: string) { const [value, setValue] = useState(initial); useEffect(() => { const stored = localStorage.getItem(key); if (stored !== null) setValue(stored); }, [key]); const set = (next: string) => { setValue(next); localStorage.setItem(key, next); }; return [value, set] as const; }Authored expected output: The hook starts from initial, loads the stored value after mount, and persists changes.
Starting from initial keeps the first render consistent on the server and client. The effect loads the stored value after mount, and set writes both state and storage.
Exercise 3Debug
This custom hook breaks the rules of hooks. Explain and fix.
starter.tsxfunction useFeature(flag: boolean) { if (flag) { const [on, setOn] = useState(false); return on; } return false; }Reveal the reference answer
reference.tsxfunction useFeature(flag: boolean) { const [on] = useState(false); return flag && on; }Authored expected output: The hook calls useState unconditionally and returns the combined result.
Calling a hook inside a condition changes the number of hooks between renders and breaks React's hook order. Move the hook call to the top level and apply the condition to the returned value.
Exercise 4Explain
Explain the difference between sharing logic and sharing state, using a custom hook example.
starter.tsx// useToggle in two componentsReveal the reference answer
reference.tsxA custom hook shares logic: the code that creates state and updates it. Each component that calls the hook gets its own independent state, so toggling one does not affect the other. To share the same state, you must lift it to a common ancestor or put it in context, and have the hook read that shared source. The distinction matters because developers often expect a hook to be a singleton, but it is a function that runs per component.Authored expected output: A written explanation that hooks reuse logic while state stays per call, plus how to share state.
The key idea is that a hook is a function, not a store. State is created per call; sharing requires an external source.
Common misconceptions
#- Custom hooks share state between components. Each call gets its own state; share state by lifting or context.
- Hooks can be called conditionally inside a custom hook. The rules of hooks still apply.
- A custom hook can be named anything. It must start with use so React can enforce the rules.
- Every repeated line should become a hook. Extract when the logic is genuinely shared and clear.
Follow-up practice
#- react-component-architecture
- react-component-testing
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.