Custom Hooks & Encapsulated State Machines
Custom hooks extract stateful logic out of component rendering functions into reusable, testable functions. A custom hook is simply a JavaScript function whose name starts with use and which may call other React hooks (useState, useEffect, useRef).
When designing custom hooks, expose a clean contract: return only the necessary state values and action callbacks the consumer needs. To prevent infinite render loops when custom hook callbacks are passed to downstream useEffect dependency arrays, memoize returned functions with useCallback.
Exercise
Build a useLocalStorage<T>(key: string, initialValue: T) hook that synchronizes state with local storage.
Check your understanding
Why must custom hook names start with 'use'?Show answerHide answer
Answer
React's linter plugins use the 'use' prefix to enforce the Rules of Hooks (e.g., not calling hooks inside loops or conditions).What is a stale closure in custom hooks?Show answerHide answer
Answer
When a callback captures variables from a past render because dependency arrays were omitted or left incomplete.