Custom Hooks
Custom hooks are JavaScript functions whose names start with "use" and can call other React hooks to share stateful logic.
Mental Model
"The Swiss Army Tool: You package reusable tools (knife, scissors, bottle opener) into one pocketable knife handle."
Interactive Engine Simulation
Invariant:The stability of this sequence is what allows React to persist state across asynchronous render cycles.
Executable Code Snippet
1// Logic extraction
2function useWindowWidth() {
3 const [width, setWidth] = useState(window.innerWidth);
4 useEffect(() => {
5 const handleResize = () => setWidth(window.innerWidth);
6 window.addEventListener('resize', handleResize);
7 return () => window.removeEventListener('resize', handleResize);
8 }, []);
9 return width;
10}- 01.Component re-renders are triggered by state or prop changes.
- 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
- 03.Automatic batching optimizes multiple state updates into a single render cycle.
01. Logic as a System
Custom hooks allow you to extract component logic into reusable functions. Crucially, **Custom hooks can use other hooks**. This allows you to build complex systems (like data fetching or form management) that remain isolated from the UI presentation layer.
Extraction Pattern
02. Shared Logic, Not Shared State
Remember: Custom hooks are a mechanism to reuse **stateful logic**, not the state itself. Each time you call a custom hook, all state and effects inside it are totally isolated. If two components use `useWindowWidth`, they both get their own independent event listeners.
Architectural Advice
"If a component's body is mostly hook calls and logic, extract it. A clean component should focus on mapping data to UI. Moving logic to hooks makes it unit-testable in isolation."