Custom Hooks
Custom Hooks
💡 Why should you learn this?
Concept
Custom hooks are a core pattern in React 19 that separates state logic from components and turns it into reusable, testable units. In professional development, they are an essential technique for reducing component complexity and boosting team-wide productivity.
Why does it matter?
In large-scale services, when multiple components repeatedly implement the same state logic (API calls, form validation, localStorage, etc.), code duplication and bugs increase rapidly. For example, if login state management logic is scattered across 10 components, changing the authentication method requires modifying all 10 places.
Core concept
Custom hooks are like a shared toolbox. Just as you would store commonly used tools like screwdrivers and wrenches in one toolbox rather than keeping a separate set in every room, you centralize the state logic shared across multiple components by extracting it into a custom hook.
Key points
- ▸Created by combining React built-in hooks using a function name that starts with
use - ▸Returns state and state manipulation functions as an object or array to maximize reusability
- ▸Completely decoupled from component logic, making unit testing very straightforward
💡 ⚠️ Common mistakes
- ▸Calling other hooks conditionally inside a hook, violating React hook rules (hooks must always be called in the same order)
- ▸Incorrectly setting the dependency array, causing infinite re-renders (mistakes managing
useCallbackanduseEffectdependencies) - ▸Packing too many responsibilities into a single custom hook, violating the single responsibility principle (a large hook like
useEverything)
💡 🎯 Interview prep
Q: What is the difference between a custom hook and a regular function?
Q: How do you test a custom hook?
Q: When do you think you should create a custom hook?
Hints: 1) Custom hooks can use React built-in hooks and participate in the component lifecycle. 2) Unit testing is possible using renderHook and act. 3) Consider extracting when the same state logic is repeated in two or more components.
⚛️ React Pattern — Custom Hooks
const [count, setCount] = useState(0);
return <h1>Current count: {count}</h1>;
<button onClick={() => setCount(count + 1)}>+1</button>