Custom Hooks
Definition
A Custom Hook is a JavaScript function whose name starts with 'use' and that may call other Hooks. It is the primary mechanism for reusing stateful logic across multiple React components.
Explain Like I'm New
Imagine you have two different robots: one cleans the floor, one washes the dishes. Both robots need to know what time it is so they know when to start. Instead of building a clock inside the floor robot, and another clock inside the dish robot, you build a separate 'Clock Module' (a Custom Hook). You plug this module into both robots. Now they both share the exact same time-telling logic without copy-pasting the code.
Real World Example
If you need to fetch data from an API in 5 different components, you don't write `useEffect` and `fetch()` 5 times. You create a `useFetch(url)` custom hook, and simply call `const { data, loading } = useFetch('/api/users')` in any component that needs it.
Common Use Cases
- •Abstracting complex API fetching logic
- •Managing form state and validation across different forms
- •Listening to global events like window resizing or dark mode toggles
Interactive Example
import { useState, useEffect } from 'react'; // 1. Define the Custom Hook function useWindowWidth() { // State to hold the width const [width, setWidth] = useState(typeof window !== 'undefined' ? window.innerWidth : 0); useEffect(() => { // The side effect logic const handleResize = () => setWidth(window.innerWidth); window.addEventListener('resize', handleResize); // Cleanup return () => window.removeEventListener('resize', handleResize); }, []); // Return the data we want components to use return width; } // 2. Use the Custom Hook in a component export default function ResponsiveComponent() { const currentWidth = useWindowWidth(); return ( <div> <h2>Window Width: {currentWidth}px</h2> {currentWidth < 600 ? <p>Mobile View</p> : <p>Desktop View</p>} </div> ); }
Interview Questions
basic
- What is the naming convention for a custom hook?
- Can a custom hook call other built-in hooks?
intermediate
- If two components use the same custom hook, do they share state?
- Why must custom hooks start with 'use'?
advanced
- How do you test a custom hook that uses context or side effects?
- Can you conditionally call a custom hook inside a component?
trick
- Does a custom hook have to return an array like `useState`?