Q13: What are Custom Hooks and what problem do they solve?

Custom Hooks are JavaScript functions whose names start with use that can call other React Hooks. They allow extracting and sharing stateful logic across multiple components without altering component hierarchy structures (unlike older Render Props or HOC patterns).

Custom Window Width Hook
function useWindowSize() {
  const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight });
  
  useEffect(() => {
    const handleResize = () => setSize({ width: window.innerWidth, height: window.innerHeight });
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return size;
}
💡 Components using useWindowSize() encapsulate window resize listener subscriptions cleanly.
Key Takeaways
  • Extracts reusable stateful logic without duplicating code.
  • State inside custom hooks is isolated per component instance.
Knowledge Check

If two separate components call the same custom hook useFetchData(), do they share state variables?