How does the useEffect hook work?
The useEffect
Hook lets you perform side effects in function components — things like data fetching, manual DOM manipulation, subscriptions, timers, and more.
How it works:
useEffect
runs after the render is committed to the screen.- You can specify dependencies; when they change, the effect runs again.
- You can return a cleanup function from the effect to clean up resources like event listeners or timers.
Syntax:
useEffect(() => { // code to run after render return () => { // cleanup code here }; }, [dependencies]);
If you provide an empty dependency array []
, the effect runs only once after the first render — similar to componentDidMount
in class components.
Perfect! Continuing with the next set: