Sub topic 1
What Effects are actually for
Many React bugs and slow components come from one habit: reaching for useEffect whenever something needs to "happen." This chapter gives you a working model of what an Effect is, when it runs, and the one question that tells you whether you need one.
Prerequisites
This chapter assumes you already know:
- How to write function components and JSX.
- How to hold state with
useStateand pass data through props. - The basic shape of
useEffect(setup, dependencies), including the dependency array. - That React re-renders a component when its state or props change.
You do not need to know useMemo, useSyncExternalStore, or key behavior yet. Later chapters cover them.
The working model
React components do two different kinds of work.
- Rendering turns props and state into JSX. React calls your component function to find out what the screen should look like. This work must be a pure calculation: the same props and state give the same JSX, and nothing outside the component changes.
- Everything else is work that reaches outside React. Examples are opening a network connection, calling
dialog.showModal()on a DOM node, starting a timer, or telling a third-party chart library to redraw.
Event handlers and Effects are the two places for the second kind of work. They differ in what triggers them:
- An event handler runs because the user did something, such as a click, a keystroke, or a form submit.
- An Effect runs because the component was displayed on screen, or because a value it depends on changed.
React's documentation describes an Effect as a way to synchronize a component with a system outside React. Synchronize is the key word. An Effect does not mean "run this code after state changes." It means "keep this outside system matching what the component currently shows."
When an Effect runs
An Effect never runs during rendering. React renders first, updates the DOM, lets the browser paint, and then runs your Effect. That is why an Effect can safely touch things that only exist after rendering, such as DOM nodes.
The timing has a consequence that matters for the rest of this tutorial. If an Effect calls setState, React must render a second time with the new value. The first render, with the stale value, has already been committed to the screen. You pay for an extra pass and risk a visible flicker.
You can see the order for yourself:
import { useState, useEffect } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
console.log('render, count is', count);
useEffect(() => {
console.log('effect ran, count is', count);
return () => {
console.log('cleanup for count', count);
};
}, [count]);
return <button onClick={() => setCount(count + 1)}>Clicked {count}</button>;
}After one click you will see render, count is 1, then cleanup for count 0, then effect ran, count is 1. React runs the cleanup from the previous render before it runs the new setup. The render log always comes first.
An Effect is synchronization, not a lifecycle hook
A common mental model is "run this on mount" or "run this when x changes." That model leads you to write Effects for logic that has nothing to do with outside systems. A better model asks what outside system the component must stay in line with, and how to start and stop that link.
Here is a legitimate Effect. The <dialog> element is a browser object. React does not own its open or closed state, so the component must push isOpen into it:
import { useEffect, useRef } from 'react';
export default function Modal({ isOpen, children }) {
const ref = useRef(null);
useEffect(() => {
if (!isOpen) {
return;
}
const dialog = ref.current;
dialog.showModal();
return () => {
dialog.close();
};
}, [isOpen]);
return <dialog ref={ref}>{children}</dialog>;
}The Effect has three parts:
- Setup:
dialog.showModal()connects the outside system to the current value. - Cleanup:
dialog.close()undoes the setup. - Dependencies:
[isOpen]lists the reactive values the Effect reads. React runs the cleanup and setup again when one of them changes.
Other typical synchronization targets are:
- Network connections such as WebSockets.
- Timers and animation loops.
- Event listeners on
windowordocument. - Non-React widgets, such as a map or a chart instance.
- Analytics events that fire because a screen was displayed.
Why Effects need cleanup
Each Effect describes one start-and-stop cycle. React may run that cycle many times: once per dependency change, and again if the component leaves and returns. Without cleanup, listeners and connections pile up. With cleanup, your component can be shown, hidden, and shown again without leaking resources.
React's development builds check this for you. In Strict Mode, React deliberately runs setup, then cleanup, then setup once more when a component first mounts. If your Effect is a clean start-and-stop cycle, you will not notice. If it breaks, you will see doubled requests, doubled listeners, or an error. The bug was already in the code. Strict Mode only exposes it early.
The one question to ask
Before writing useEffect, ask:
Is there an outside system that this component needs to stay in sync with?
- If the answer is yes, an Effect is probably right.
- If the answer is no, you probably do not need one.
Without an outside system, an Effect is only React talking to itself. Typical examples are an Effect that reads state and sets other state, or one that reacts to a click that already had its own handler. Both can be replaced by something simpler.
A second question sharpens the first: why does this code need to run?
| Reason the code runs | Where it belongs |
|---|---|
| The component was displayed, or a value used to talk to an outside system changed | Effect |
| The user did something specific, such as clicking or submitting | Event handler |
| It computes a value from existing props or state | Calculate during render |
| It resets state when the identity of the thing shown changes | A `key` on the component |
| It reads a value that lives outside React and changes over time | `useSyncExternalStore` |
The remaining chapters of this tutorial work through each row in turn.
A before-and-after example
Here is a typical unnecessary Effect. The component stores fullName in state and keeps it up to date with an Effect:
import { useState, useEffect } from 'react';
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
const [fullName, setFullName] = useState('');
// Avoid: redundant state and an Effect that only updates it.
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
return (
<>
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
<input value={lastName} onChange={e => setLastName(e.target.value)} />
<p>{fullName}</p>
</>
);
}Trace what happens when the user types one letter:
setFirstNameruns, so React renders. The newfirstNameis on screen, butfullNameis still old.- React commits to the DOM. The paragraph shows a stale name.
- The Effect runs and calls
setFullName. - React renders a second time, and the paragraph finally updates.
There are two render passes, a moment of inconsistent data, and a fullName variable that can drift out of sync with its sources. The fix is to calculate the value in the component body:
import { useState } from 'react';
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
// Calculated during render. No extra state and no Effect.
const fullName = firstName + ' ' + lastName;
return (
<>
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
<input value={lastName} onChange={e => setLastName(e.target.value)} />
<p>{fullName}</p>
</>
);
}One render pass, and fullName cannot be stale because it is rebuilt every time.
Common errors
These are the mistakes this tutorial will teach you to spot.
- Mirroring state. Copying props or state into new state, then syncing it with an Effect. The copy is redundant and can go stale.
- Reacting to your own click. Running a
POSTrequest from an Effect that watches a flag set inonClick. The request belongs in the handler, as the user caused it. - Chaining Effects. One Effect sets state, which triggers a second Effect, which sets more state. Each link costs a render and makes the flow hard to follow.
- Notifying a parent from an Effect. Calling
onChangein an Effect after local state changes. The parent update happens in a later pass, not in the same batch as the event. - Forgetting cleanup. Subscribing, connecting, or fetching without a way to undo or ignore the work.
- Silencing the dependency linter. If the linter says a dependency is missing, the Effect is reading a value it does not react to. Disabling the warning hides a real bug rather than fixing it.
Where Effects are still the right tool
Removing unnecessary Effects does not mean avoiding them. Two cases stay with Effects:
- Synchronizing with an outside system that React does not control, as the dialog example showed.
- Fetching data because a component is displayed, where the request is a consequence of being on screen and not of a particular click. This needs cleanup so that a slow, outdated response does not overwrite a newer one. A later chapter covers this in detail.
A short preview of the data-fetching shape shows the cleanup idea you have just learned:
import { useState, useEffect } from 'react';
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
let ignore = false;
fetch('/api/search?q=' + encodeURIComponent(query))
.then(response => response.json())
.then(json => {
if (!ignore) {
setResults(json);
}
});
return () => {
ignore = true;
};
}, [query]);
return (
<ul>
{results.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}When query changes, React runs the cleanup for the old query first, which flips ignore to true. If the old response arrives late, it is dropped.
Summary of the working model
- Rendering calculates JSX from props and state. It must stay pure.
- Event handlers run code because the user did something.
- Effects run code after render to keep an outside system in sync with the component.
- An Effect that only moves data from one piece of React state to another is almost always a sign of a simpler design.
- When you do write an Effect, give it a cleanup that reverses its setup, and list every reactive value it reads.
Exercise
A component keeps items in state and also keeps itemCount in state. An Effect with [items] as its dependency calls setItemCount(items.length). Does this component need an Effect? What should it do instead, and what extra work does the Effect cause?
Show answer
It does not need an Effect, because no outside system is involved. Remove the itemCount state and the Effect, and write const itemCount = items.length; in the component body. The Effect causes a second render on every change to items. The first render shows a stale count, and the second corrects it.
Exercise
Which of these belong in an Effect, and which do not? (a) Subscribing to a WebSocket room whose ID comes from props. (b) Sending a purchase request when the user clicks "Buy." (c) Building a filtered list from todos and filter.
Show answer
Only (a) belongs in an Effect. The component must stay connected to an outside system, and the Effect needs a cleanup that disconnects. (b) belongs in the click handler because the user's action causes it. (c) is a value calculated during render.
Exercise
In the Strict Mode development build, you see your Effect's setup run, then cleanup, then setup again when the component first appears. Is this a bug in React? What should you check in your Effect?
Show answer
It is not a bug. React does this on purpose to test that your Effect is a clean start-and-stop cycle. Check that the cleanup fully reverses the setup, for example by removing the listener, closing the connection, or ignoring the stale response. If the Effect behaves correctly when run, cleaned up, and run again, it passes the test.