Hooksintermediate
Custom Hooks for Logic Reuse
Learn how to extract stateful logic into reusable custom hooks that follow React's naming and rules conventions.
A custom hook is simply a JavaScript function whose name starts with use and that calls other hooks internally. It's the primary mechanism React provides for sharing stateful logic between components without resorting to older patterns like higher-order components or render props, which tend to add wrapper nesting.
A custom hook is like a recipe card you photocopy for every cook (component) who wants to make the same dish — each cook has their own kitchen and ingredients (state), but they all follow the identical set of steps written on the card.
Key Concepts
1
Custom hooks let you extract a self-contained piece of behavior — like tracking window size, debouncing a value, or managing a fetch request's loading/error/data states — into a function that any component can call. Each component that calls the custom hook gets its own independent state; the hook is a reusable recipe, not a shared instance.
2
Because a custom hook is 'just a function that calls hooks,' it must obey the same Rules of Hooks as any hook usage: called unconditionally at the top level, and only from React function components or other hooks. The use naming convention isn't just a convention — React's linter uses it to know which functions to check for hook rule violations.
use
3
Interviewers frequently ask candidates to design a custom hook live, such as useLocalStorage or useDebounce, to assess whether they understand encapsulating side effects cleanly, returning a clear and minimal API, and correctly listing dependencies inside the hook's own internal effects.
useLocalStorageuseDebounce