What are custom hooks in React?
Why Interviewers Ask This
This question targets practical, hands-on experience with React.js. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
Custom hooks are JavaScript functions whose names start with "use" that call other hooks inside them. They allow extracting and reusing stateful logic across multiple components. Example: function useWindowSize() { const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight }); useEffect(() => { const handler = () => setSize({ width: window.innerWidth, height: window.innerHeight }); window.addEventListener("resize", handler); return () => window.removeEventListener("resize", handler); }, []); return size; }. Usage: const { width, height } = useWindowSize();. Why custom hooks are powerful: (1) Extract complex logic from components into testable, reusable functions. (2) Share stateful logic without render props or HOCs (no wrapper hell). (3) Each call to a custom hook has isolated state — two components using the same hook do not share state. (4) They compose naturally — custom hooks can call other custom hooks. Common custom hooks: useFetch, useLocalStorage, useDebounce, useInterval, usePrevious, useMediaQuery. The only rule: custom hook names must start with "use" so React can enforce hook rules.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex React.js answers easy to follow.
Previous
What is the difference between findDOMNode and ref?
Next
What are the rules of hooks in React?