Sub topic 3
Calculate values during render instead of syncing state
This chapter assumes you know function components, useState, props, and the basics of useEffect with its dependency array. You should also know that React re-renders a component when its state or props change.
The problem: state that mirrors other state
A common mistake is to store a value in state when you can compute it from state or props you already have. You then add an Effect to keep the copy in sync.
import { useState, useEffect } from 'react';
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
// Avoid: redundant state and an unnecessary Effect
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
return <p>{fullName}</p>;
}This code has three costs:
- Extra render pass. React renders with the old
fullName. The Effect runs after that render and callssetFullName. React then renders again with the new value. - A stale frame. For one render,
fullNamedoes not matchfirstNameandlastName. The screen can show an inconsistent value before the second render fixes it. - More code to get wrong. You must keep the dependency array correct, and every place that changes the inputs depends on the Effect to repair the copy.
The fix: calculate it during render
Rendering is a calculation of your props and state. If a value can be computed from them, compute it 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>
</>
);
}When firstName or lastName changes, React re-renders once. The body runs again and fullName is correct from the first moment it is displayed. There is nothing to synchronize because there is only one source of truth.
How to spot the pattern
Look for these signs in your code:
- A
useStatewhose value is always set from other values. - A
useEffectwhose only job is to call a setter. - A dependency array that lists exactly the values used to compute that setter's argument.
If all three are present, delete the state and the Effect, and replace them with a plain variable.
This applies to more than string concatenation. Filtering a list, counting items, sorting, and formatting a date are all derived values. For example, if you keep todos and filter in state, compute the visible list from them instead of storing visibleTodos.
Common errors
| Mistake | Why it is a problem | Fix |
|---|---|---|
| Copying a prop into state to "keep it" | The state ignores later prop changes | Use the prop directly |
| Storing a filtered or sorted array in state | It can fall out of sync with the source list | Compute it in the body |
| Setting state in an Effect that depends on that same state's inputs | Causes an extra render and can loop | Calculate during render |
Copying a prop into state is only correct when you want it as an initial value that the component then owns. Name such props initialX so readers know later changes are ignored.
When the calculation is slow
Calculating during render runs the code on every render. For a string join, that cost is negligible. For a calculation that is slow, the next chapter shows how useMemo caches the result. Even then, you still do not need an Effect.
Exercise
A component keeps items and query in state. It also has const [filtered, setFiltered] = useState([]) and an Effect with dependencies [items, query] that calls setFiltered(items.filter(i => i.name.includes(query))). Rewrite it so there is no extra state and no Effect.
Show answer
Remove filtered and the Effect. Write const filtered = items.filter(i => i.name.includes(query)); in the component body. It is recalculated on every render, so it always matches items and query, and React renders once per change instead of twice.
Exercise
Why can the Effect version of fullName show a wrong value for one render?
Show answer
React renders first with the old fullName. The Effect runs only after that render finishes, and the new value appears only after setFullName triggers a second render.