Back to results for “Hooks”
React › Custom Hooks

What is a custom hook in React and why would you create one?

Beginner

Answer

A custom hook is simply a JavaScript function whose name starts with use, and it lets you reuse stateful logic between different components without repeating the same code. It can call other hooks inside it, like useState or useEffect, just like a regular component can.
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    function handleResize() { setWidth(window.innerWidth); }
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return width;
}
Real-world example A shopping site uses a single useWindowWidth custom hook in both its navigation bar and its product grid, so both components can react to screen size changes without duplicating the same resize logic twice.

Common follow-ups: Why must a custom hook's name always start with the word use?;Can a custom hook call another custom hook inside it?