Sub topic 9
When you do not need an effect
This chapter assumes you know function components, useState, how state changes trigger re-renders, and the basics of useEffect and its dependency array.
The common mistake
An effect is for synchronizing with something outside React: the DOM, a network, a timer. Many effects in real code do none of that. They copy one piece of React data into another piece of state. This costs you an extra render pass and creates two sources of truth that can drift apart.
Here is the pattern to recognize:
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>;
}In the first version, a change to query causes this sequence:
- React renders with the old
visiblelist. - React commits that output to the screen.
- The effect runs and calls
setVisible. - React renders again with the new list.
For one frame, the screen shows a list that does not match the query. The second version computes visible in the same render, so the output is always consistent.
A rule of thumb
Ask what the value depends on.
- If it can be calculated from current props and state, calculate it during rendering. Do not store it in state.
- If it is the result of a user action such as a click or a submit, put the logic in an event handler.
- If the component must stay in sync with an external system while it is on screen, use an effect.
Other cases where an effect is unnecessary
| Situation | Instead of an effect |
|---|---|
| Filtering, sorting or formatting data | Compute it in the render body |
| Expensive calculation that is slow on every render | Wrap it in `useMemo` after you measure a real problem |
| Resetting all state when a prop changes | Give the component a different `key` |
| Sending a request after a button click | Call it from the click handler |
| Notifying a parent after a change | Call the parent's callback in the same event handler that changed the state |
The key approach deserves an example. When userId changes, a different key tells React to discard the old component and create a new one with fresh state:
function ProfilePage({ userId }) {
return <Profile key={userId} userId={userId} />;
}Common errors
- Storing a derived value in state and updating it from an effect. Delete the state and compute the value.
- An effect whose only job is to call
setStatebased on other state. This often signals derived state, and it can also cause render loops. - Running a "user did X" action in an effect. The effect also fires when dependencies change for other reasons, such as a remount in development, so the action can run at the wrong time.
Exercise
A component receives a price prop and a taxRate prop. A developer stores total in state and updates it with useEffect(() => setTotal(price * (1 + taxRate)), [price, taxRate]). How should this be rewritten, and why?
Show answer
Remove the total state and the effect, and write const total = price * (1 + taxRate); in the render body. The value can be calculated from props, so computing it during rendering avoids a second render and prevents total from showing a stale value for one frame.
Exercise
A form should call sendAnalytics('submitted') when the user clicks Submit. Should this go in an effect that watches a submitted state flag, or in the click handler?
Show answer
In the click handler. The action is caused by a specific user event, not by the component being on screen. An effect watching a flag adds an extra render and can fire again for unrelated reasons.