Sub topic 9
When you do not need an effect
This chapter assumes you can write function components, use useState, and read a useEffect call with its dependency array and cleanup function. It also assumes you know that React calls your component to render, then commits the result to the DOM.
An effect synchronizes a component with something outside React, such as the network, a timer, a browser API, or a non-React widget. Many effects in real code do something else. They copy one piece of React data into another piece of React data. Those effects are slower and easier to break than the alternatives. This chapter shows how to spot them and what to write instead.
Why unnecessary effects cost you
When an effect calls setState, React has to run the whole cycle again:
- React renders the component with the old state.
- React commits the result to the DOM, and the browser may paint it.
- React runs the effect, which calls
setState. - React renders again with the new state and commits again.
Between steps 2 and 4 the screen shows a stale value for a moment. The extra render is also easy to get wrong. If the effect forgets a dependency, the copy in state silently drifts away from its source.
Derive values during rendering
If a value can be calculated from props or state, calculate it in the render body. Do not store it in state.
import { useEffect, useState } from 'react';
// Avoid: an effect that copies props into state
function FilteredListWithEffect({ items, query }) {
const [visible, setVisible] = useState([]);
useEffect(() => {
setVisible(items.filter((i) => i.name.includes(query)));
}, [items, query]);
return <ul>{visible.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
}
// Prefer: compute the value during rendering
function FilteredList({ items, query }) {
const visible = items.filter((i) => i.name.includes(query));
return <ul>{visible.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
}The first version renders once with visible empty, then renders again after the effect runs. The second version is correct on the first render and cannot fall out of sync, because there is only one source of truth.
A useful rule is to keep state minimal. Store the smallest amount of data that cannot be calculated, and derive everything else. A full name is first + ' ' + last, a total is a sum over the cart, and a "form is valid" flag is a check over the fields. None of these needs its own state variable.
Expensive calculations
If the calculation is slow, wrap it in useMemo instead of moving it into an effect. useMemo caches the result between renders until a dependency changes.
import { useMemo } from 'react';
function TodoList({ todos, filter }) {
const visible = useMemo(
() => todos.filter((t) => (filter === 'done' ? t.done : !t.done)),
[todos, filter]
);
return (
<ul>
{visible.map((t) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
);
}useMemo is a performance hint, not a correctness feature. Do not add it by default. Time the calculation first, for example with console.time. A filter over a few hundred items usually takes well under a millisecond and does not need caching. The memoized value is also only as stable as its dependencies. If todos is a new array on every render, the cache never hits.
Reset state with a key, not an effect
A common pattern resets state when a prop changes:
// Avoid
useEffect(() => {
setComment('');
}, [userId]);This shows the old comment for one render, then clears it. It also has to be repeated for every state variable that should reset. React offers a better tool. When a component's key changes, React discards the old instance and creates a new one with fresh state.
import { useState } from 'react';
export default function ProfilePage({ userId }) {
// A new key means a new Profile instance with fresh state
return <Profile userId={userId} key={userId} />;
}
function Profile({ userId }) {
const [comment, setComment] = useState('');
return (
<section>
<h2>Comments for user {userId}</h2>
<textarea value={comment} onChange={(e) => setComment(e.target.value)} />
</section>
);
}Everything inside Profile resets, including its child components. That is usually what you want when the identity of the thing being edited changes. If you want to reset only one variable, use the next technique.
Store an ID, not a copy of the object
Another common mistake is keeping a selected object in state and then using an effect to clear or update it when the list changes.
import { useState } from 'react';
function PickList({ items }) {
const [selectedId, setSelectedId] = useState(null);
// Derived on every render, so it always matches the current items
const selected = items.find((i) => i.id === selectedId) ?? null;
return (
<div>
<ul>
{items.map((i) => (
<li key={i.id}>
<button onClick={() => setSelectedId(i.id)}>{i.name}</button>
</li>
))}
</ul>
<p>{selected ? `Selected: ${selected.name}` : 'Nothing selected'}</p>
</div>
);
}If the selected item is removed from items, find returns undefined and the UI shows "Nothing selected". No effect is needed. If you had stored the whole object, it would keep showing a stale copy of an item that no longer exists.
Put user-caused logic in event handlers
If something happens because the user clicked, typed, or submitted, run it in the handler for that event. An effect cannot tell why a value changed. It only sees that the value is different.
import { useState } from 'react';
function Toggle({ onChange }) {
const [on, setOn] = useState(false);
function update(next) {
setOn(next);
onChange(next); // notify the parent in the same event
}
return <button onClick={() => update(!on)}>{on ? 'On' : 'Off'}</button>;
}The effect version looks like this: useEffect(() => { onChange(on); }, [on, onChange]);. It has three problems:
- It calls
onChangeon mount, before the user has done anything. - It runs again whenever the parent passes a new
onChangefunction, even thoughondid not change. - The parent's state update happens in a separate render pass after the child's.
The same reasoning applies to sending a POST request when a form is submitted, showing a notification after a purchase, or logging an analytics event for a click. The user action is the cause, so the handler is the place for the code. Reserve effects for things that happen because the component was displayed, such as a page-view event.
Quick reference
| Pattern you see | Why it is a problem | Use instead |
|---|---|---|
| Effect that calls `setX(f(props))` | Extra render, value can be stale | Compute `f(props)` in the render body |
| Effect that resets state when a prop changes | Flash of old state, repeated for every variable | `key` on the component |
| Effect that adjusts a selected object when a list changes | Stale copy | Store the ID, derive the object |
| Effect that runs after `setState` to notify a parent | Runs on mount, depends on function identity | Call the callback in the event handler |
| Effect that POSTs because a button was clicked | Cannot tell why the value changed | Do it in the click or submit handler |
| Chain of effects, each setting state for the next | Many renders, hard to follow | Calculate everything in one handler or one render |
When an effect is still the right tool
Removing unnecessary effects does not mean avoiding useEffect. Keep an effect when the code needs to stay in sync with a system outside React and the reason is that the component is on screen:
- Subscribing to a WebSocket, a store, or a browser event.
- Starting a timer or animation.
- Fetching data that the displayed UI needs. Many frameworks and data libraries handle this better than a hand-written effect, but a well-written effect with cleanup is acceptable.
- Controlling a non-React widget, such as calling
.play()on a video element.
A good test is to ask what you are synchronizing with. If the answer is "another piece of React state", you probably do not need an effect. If the answer is "the network, the DOM API, or a library", an effect fits.
Exercise
Exercise
A component receives a products array and a maxPrice number as props. It keeps cheap in state and updates it with useEffect(() => { setCheap(products.filter(p => p.price <= maxPrice)); }, [products, maxPrice]);. Rewrite it without an effect, and name two problems with the original.
Show answer
Replace the state and effect with const cheap = products.filter((p) => p.price <= maxPrice); in the render body. The original renders once with an empty or outdated cheap before the effect runs, which causes a second render and a brief flash of wrong content. It also stores a value that is already determined by products and maxPrice, so the copy can fall out of sync if a dependency is missed. If the filter were slow, wrap the calculation in useMemo with [products, maxPrice] instead of using an effect.
Exercise
A Editor component takes a documentId prop and holds text and isDirty in state. When the user opens a different document, both must reset. What is the simplest fix, and why is it better than an effect with setText('') and setIsDirty(false)?
Show answer
Render the editor with key={documentId}, for example <Editor documentId={documentId} key={documentId} />. When the key changes, React creates a new instance with fresh state, so both variables reset together. The effect version would show the old text for one render, and you would have to remember to reset every new state variable you add later.