The useEffect Hook

How to synchronize your React components with external systems like APIs, databases, or the browser DOM.

React4 min readConcept 13 of 46

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.

function ChatRoom() {
useEffect(() => {
// 1. Setup: Runs AFTER component mounts
const connection = createConnection();
connection.connect();
 
// 2. Cleanup: Runs BEFORE component unmounts
return () => {
connection.disconnect();
};
}, []); // Empty array = run once on mount
 
return ;
}
Component Destroyed
Server Logs
Waiting for connection...

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.

  1. 1When does the code inside a `useEffect` function actually execute?
  2. 2Why shouldn't you make an API call directly in the main body of your component?
  3. 3How do you clean up a subscription or timer started inside a `useEffect`?

Remember this

  • Use useEffect for 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.