0
0
Reactframework~10 mins

Custom hook best practices in React - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom hook best practices
Start: Component needs reusable logic
Create custom hook function
Use React hooks inside custom hook
Return needed state and functions
Use custom hook in component
Component uses returned values
Update state triggers re-render
End
This flow shows how a component uses a custom hook to share logic, with the hook managing state and returning values for the component to use.
Execution Sample
React
import { useState, useEffect } from 'react';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return width;
}

function MyComponent() {
  const width = useWindowWidth();
  return <div>Width: {width}px</div>;
}
This code defines a custom hook to track window width and uses it in a component to display the current width.
Execution Table
StepActionState BeforeState AfterComponent Render Output
1MyComponent mounts, calls useWindowWidthwidth: undefinedwidth: window.innerWidth (e.g. 1024)Width: 1024px
2useEffect adds resize event listenerwidth: 1024width: 1024Width: 1024px
3Window resized to 800px, event triggers handleResizewidth: 1024width: 800Width: 800px
4Component re-renders with new widthwidth: 800width: 800Width: 800px
5Component unmounts, cleanup removes event listenerwidth: 800N/AComponent removed
6No further updatesN/AN/ANo output
💡 Component unmounts and event listener is cleaned up, stopping updates.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
widthundefined1024800800
Key Moments - 3 Insights
Why do we add and remove the event listener inside useEffect?
Because useEffect runs after the component mounts, adding the listener once, and returns a cleanup function to remove it when the component unmounts, preventing memory leaks. See execution_table steps 2 and 5.
Why must the custom hook name start with 'use'?
React relies on the 'use' prefix to identify hooks and enforce rules. Without it, React won't apply hook behavior correctly, causing errors.
What happens if we don't return values from the custom hook?
The component won't get the needed data or functions to use, so it can't respond to state changes. Returning values connects the hook's logic to the component. See execution_table step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'width' after step 3?
A800
B1024
Cundefined
D0
💡 Hint
Check the 'State After' column for step 3 in the execution_table.
At which step is the event listener removed?
AStep 4
BStep 5
CStep 2
DStep 6
💡 Hint
Look for cleanup actions in the execution_table rows.
If the custom hook did not return 'width', what would the component render?
AWidth: 0px
BWidth: 1024px
CWidth: undefinedpx
DAn error
💡 Hint
Refer to variable_tracker and how the component uses the returned value.
Concept Snapshot
Custom hooks start with 'use' and contain React hooks.
Use useEffect for side effects and cleanup.
Return state and functions to share logic.
Use them inside components like normal hooks.
They help reuse logic cleanly and keep components simple.
Full Transcript
Custom hooks in React are functions that start with 'use' and let you reuse stateful logic across components. They use React hooks like useState and useEffect inside. When a component calls a custom hook, it gets back state or functions to use. The hook can set up side effects like event listeners and clean them up when the component unmounts. This keeps code organized and avoids repeating logic. For example, a useWindowWidth hook tracks the window size and updates state on resize. The component uses this hook to display the current width. The hook adds the resize listener on mount and removes it on unmount to prevent memory leaks. Returning values from the hook connects its logic to the component's render. Always name custom hooks starting with 'use' so React treats them correctly.