The useEffect Hook
How to synchronize your React components with external systems like APIs, databases, or the browser DOM.
What it is
useEffect is a React Hook that lets you execute side effects in your components. A 'side effect' is any code that affects something outside the scope of the function being executed.
Examples include: fetching data from an API, setting up a subscription, manually changing the DOM, or starting a timer.
Why it matters
React components are supposed to be **pure functions**. They should only take inputs (props/state) and return JSX. If you fetch data directly in the component body, it will fetch that data *every single time* the component re-renders (which could be 60 times a second!).
useEffect tells React: 'Hey, render the UI first so the user sees it, and *then* run this side effect.'
How to use it
You pass a function to useEffect. By default, this function runs after every render.
tsx
useEffect(() => {
document.title = 'Hello World';
});
To prevent it from running on every render, you pass a **dependency array** as the second argument. It will only re-run if one of the dependencies has changed.
The Chat Connection
Toggle the Chat component on and off. Watch how the effect connects to the server after mounting, and uses the cleanup function to disconnect when unmounting.
Toggle the ChatRoom component. Notice how the effect runs after it mounts, and the cleanup function runs right before it unmounts, preventing memory leaks.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Use
useEffectfor side effects: network requests, manual DOM mutations, and subscriptions. - Effects run *after* the render is committed to the screen.
- Provide a dependency array to control exactly when the effect re-runs.
- Return a cleanup function to remove event listeners, cancel timers, or close connections.
Done with this concept?
Mark it complete to track your progress. No login needed.