Sub topic 1
What Effects Are Actually For
This chapter explains what an Effect is for and why it runs after rendering. Later chapters replace the common unneeded Effects one at a time.
Prerequisites
This chapter assumes you know the following:
- Function components and JSX.
- State with
useState, and props. - The basic shape of
useEffectand its dependency array. - That React re-renders a component when its state or props change.
The working model
An Effect is code that synchronizes your component with a system outside React. Examples are the network, browser APIs such as document.title or localStorage, and third-party widgets like a map or a video player.
React does not control those systems. Rendering must stay a pure calculation of props and state, so React runs Effects after it has rendered and updated the screen. This means an Effect can see the finished result, and rendering is never blocked by outside work.
Two kinds of code run in a component:
| Kind of code | When it runs | What it is for |
|---|---|---|
| Rendering code | During each render | Calculating the JSX from props and state |
| Event handlers | When the user acts | Doing work caused by that action |
| Effects | After a render is committed | Staying in sync with an outside system |
The question to ask is: why does this code need to run? If it runs because the component was displayed, it may be an Effect. If it runs because the user clicked or typed, it belongs in an event handler. If it only computes a value from props and state, it belongs in the render body.
A legitimate Effect
This component keeps the browser tab title in sync with a count. The tab title is outside React, so an Effect is the right tool.
import { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = 'Clicked ' + count + ' times';
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}The render only calculates the button. The Effect runs after the screen updates and again only when count changes.
A common mistake
Many Effects do not talk to an outside system. They only move data from one piece of React state to another. Here the Effect copies a value that could be calculated directly.
import { useState, useEffect } from 'react';
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
const [fullName, setFullName] = useState('');
// Unneeded: this only mirrors other state.
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
return <p>{fullName}</p>;
}This code works, but it does extra work. React renders with a stale fullName, runs the Effect, calls setFullName, and then renders a second time. You also gain a state variable that can fall out of sync.
The fix is to calculate the value during render:
const fullName = firstName + ' ' + lastName;Common errors
- Using an Effect to update state from other state or props. Calculate the value during render instead.
- Using an Effect to respond to a click or form submit. Move that logic into the event handler.
- Adding an Effect that works but causes an extra render pass. The extra pass is a sign that the Effect is not needed.
- Forgetting that an Effect runs after render. It cannot change what the current render outputs, only what happens after it.
What comes next
The next chapters take each unneeded pattern in turn: derived values, memoization, resetting with a key, event handlers, and external stores. The final chapter returns to cases where an Effect is correct, such as data fetching with cleanup.
Exercise
A component shows a list of items and a search box. A developer stores the filtered list in state and updates it with an Effect that depends on items and query. Does this need an Effect? What would you do instead?
Show answer
No. The filtered list can be calculated from items and query, so nothing outside React is involved. Remove the state variable and the Effect, and calculate const visibleItems = items.filter(...) in the render body. If the calculation is expensive, wrap it in useMemo.
Exercise
Which of these needs an Effect? (a) Sending a POST request when the user presses Submit. (b) Setting document.title from a prop. (c) Joining firstName and lastName for display.
Show answer
Only (b). It synchronizes with the browser, which is outside React. (a) is caused by a user action, so it belongs in an event handler. (c) is a value calculated from existing state, so it belongs in the render body.