Sub topic 6
Adjusting Some State When a Prop Changes
This chapter assumes you can write function components with useState, that you know useEffect and its dependency array, and that you know a component re-renders when its state or props change. The previous chapter showed how to reset all of a component's state with a key. This chapter covers the harder case: a prop changes and only some of the state should react.
The problem
A component receives a prop and also keeps its own state. When the prop changes, part of that state no longer makes sense. A list component is a typical example. It receives items from its parent and remembers which item the user selected. If the parent passes a new list, the old selection may point at something that is gone.
The usual first attempt is an Effect that watches the prop and fixes the state:
import { useState, useEffect } from 'react';
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selection, setSelection] = useState(null);
// Avoid: an Effect that adjusts state when a prop changes
useEffect(() => {
setSelection(null);
}, [items]);
const ordered = isReverse ? [...items].reverse() : items;
return (
<>
<button onClick={() => setIsReverse(!isReverse)}>Reverse</button>
<ul>
{ordered.map(item => (
<li key={item.id}>
<button onClick={() => setSelection(item)}>
{selection && selection.id === item.id ? '> ' : ''}
{item.name}
</button>
</li>
))}
</ul>
</>
);
}This code works, but it is wasteful and can show wrong output for a moment.
Why the Effect is the wrong tool
Effects run after React has rendered and committed the result to the screen. Here is what happens when items changes:
- React renders
Listwith the newitemsand the oldselection. - React commits that output. The user's browser may paint it. The selection marker can appear on a row that no longer belongs to the selected item.
- The Effect runs and calls
setSelection(null). - React renders
Lista second time and commits again.
The first pass is a render with stale state. Child components also render with that stale value, and they may run their own Effects with it. Each extra pass costs time, and a flash of incorrect UI is possible.
The Effect also hides the relationship between the prop and the state. A reader has to follow an Effect to learn that selection depends on items. The next sections give three better options, in order of preference.
First choice: do not store it
Ask whether the state needs to exist. In the example, selection holds a whole item object. That object is a copy of something that lives in items. When items changes, the copy goes out of date.
Store the ID instead, and look up the item during render:
import { useState } from 'react';
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selectedId, setSelectedId] = useState(null);
// Calculated during render. It is null if the item is no longer in the list.
const selection = items.find(item => item.id === selectedId) ?? null;
const ordered = isReverse ? [...items].reverse() : items;
return (
<>
<button onClick={() => setIsReverse(!isReverse)}>Reverse</button>
<ul>
{ordered.map(item => (
<li key={item.id}>
<button onClick={() => setSelectedId(item.id)}>
{selection && selection.id === item.id ? '> ' : ''}
{item.name}
</button>
</li>
))}
</ul>
</>
);
}Now no adjustment is needed. If the new items still contains the selected ID, the selection survives, which is often better than clearing it. If the ID is gone, selection is null on the very first render. There is no stale pass, no Effect, and no extra state.
This is the derived-state idea from earlier chapters, applied to a prop. Whenever you can describe the adjusted value as a function of props and the remaining state, calculate it.
Second choice: reset everything with a key
If the right behavior is to throw away all of the component's state when a prop changes, give the component a key based on that prop. Use this when the prop identifies a different "thing", such as a different user or document. It does not help when only some of the state should reset, because a key resets all of it. If you can split the component so the part that should reset is its own child, you can put the key on that child.
Last resort: adjust state during render
Sometimes the state cannot be derived and a key resets too much. Consider a price field whose currency comes from a parent. The typed amount is meaningless in a different currency, so it should clear. The user's note about the payment should stay.
React allows a component to call its own set function while rendering, if the call is guarded by a condition. React then discards the output it just produced and renders the component again right away, before rendering children or committing anything to the screen. To detect the change, store the previous prop value in state and compare:
import { useState } from 'react';
function PriceInput({ currency }) {
const [amount, setAmount] = useState('');
const [note, setNote] = useState('');
const [prevCurrency, setPrevCurrency] = useState(currency);
if (currency !== prevCurrency) {
setPrevCurrency(currency);
setAmount('');
}
return (
<>
<label>
Amount ({currency}){' '}
<input value={amount} onChange={e => setAmount(e.target.value)} />
</label>
<label>
Note{' '}
<input value={note} onChange={e => setNote(e.target.value)} />
</label>
</>
);
}
export default function App() {
const [currency, setCurrency] = useState('USD');
return (
<>
<select value={currency} onChange={e => setCurrency(e.target.value)}>
<option>USD</option>
<option>EUR</option>
<option>JPY</option>
</select>
<PriceInput currency={currency} />
</>
);
}Trace the flow when the select changes from USD to EUR:
Appre-renders and passescurrency="EUR".PriceInputstarts rendering. The condition"EUR" !== "USD"is true.- It calls
setPrevCurrency("EUR")andsetAmount(''). React throws away this render's output and re-rendersPriceInputimmediately. - In the second pass,
prevCurrencyis"EUR", so the condition is false and rendering finishes normally. - React commits once. The screen never shows the old amount next to the new currency, and
notekeeps its value.
Rules for updating state during render
- Only update the component that is rendering. Calling a state setter that belongs to another component during render is a bug, and React warns about it.
- Always guard the call with a condition. An unconditional
setStatein the body re-renders forever. React stops this with a "Too many re-renders" error. - Make the condition become false after the update. In the example, storing
currencyinprevCurrencyis what ends the loop. A condition that compares against something the update does not change will loop. - Compare with the previous value, not a mutated one. Use
!==on primitives. For arrays and objects, this compares references, so a parent that builds a new array each render triggers the adjustment on every render. - Keep the render pure. Do not call APIs, write to
localStorage, or touch the DOM here. Only call state setters for this component.
Because of these rules, this pattern is an escape hatch. It is harder to read than the alternatives, and it adds a state variable only to remember the last prop.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Screen flashes old state for one frame after a prop change | An Effect adjusts the state after commit | Derive the value, or adjust state during render |
| "Too many re-renders" error | The render-time `setState` has no guard, or the guard stays true | Store the previous prop and compare against it, and update it in the same branch |
| Adjustment runs on every parent render | The prop is a new array or object each time, and the guard uses `!==` | Compare a stable value such as an ID, or memoize the prop in the parent |
| Selected item shows outdated data | State holds a copy of an object from props | Store an ID and look up the object during render |
| Warning about updating another component during render | Calling a parent's setter in the render body | Move that update to the event handler that caused the change |
| All fields reset when only one should | A `key` on a component that holds mixed state | Split the component, or adjust only the needed state |
Choosing between the options
Two practical notes on the choice:
- An Effect is still not the answer here. Even if you cannot derive the value, an Effect adds the stale render. Reach for the render-time update first.
- Consider whether the state belongs in this component. If the parent already knows when the prop changes, it may be simpler for the parent to own the state, or to reset it in the event handler that changed the prop. That removes the need to detect the change at all.
Edge cases
- Initial render.
useState(currency)forprevCurrencymakes the condition false on mount, so nothing is adjusted at startup. - Several props. You can track one
prevvalue per prop, or store a single object. Separate variables keep the comparisons simple. - Changing back and forth. Switching
USDtoEURand back toUSDtriggers two adjustments. Each clears the amount. This is usually what you want, but if you need to remember an amount per currency, store a map from currency to amount and derive the current value instead. - Strict Mode. In development, React renders components twice to find impurities. A correctly guarded render-time update still works, because the second render sees the already-updated state.
Exercise
A Cart component receives a couponCode prop and keeps quantity and giftMessage in state. When couponCode changes, quantity should return to 1, and giftMessage should stay. The current code uses useEffect(() => { setQuantity(1); }, [couponCode]);. Rewrite it so the screen never shows the old quantity with the new coupon. Which state variable do you add, and why is the update guarded?
Show answer
Add const [prevCoupon, setPrevCoupon] = useState(couponCode); and, in the component body, if (couponCode !== prevCoupon) { setPrevCoupon(couponCode); setQuantity(1); }. React re-renders immediately and commits once, so the old quantity never appears, and giftMessage is untouched. The guard is needed because an unconditional setState during render would cause an endless re-render loop. Updating prevCoupon in the same branch makes the condition false on the second pass.
Exercise
A Playlist stores currentTrack (a whole track object) from its tracks prop. After the parent refreshes tracks, the screen shows stale track titles. Without using an Effect or a render-time update, how do you fix it?
Show answer
Store the track ID in state (currentTrackId) and compute const currentTrack = tracks.find(t => t.id === currentTrackId) ?? null; during render. The title always comes from the latest tracks, and if the track is removed, currentTrack is null immediately.