Sub topic 6
Adjusting some state when a prop changes
This chapter assumes you know useState, props, and the useEffect dependency array. It also assumes you know that React re-renders a component when its state or props change.
The problem
The previous chapter used a key to reset all of a component's state when a prop changes. Sometimes you want to reset only part of the state, or adjust it. A list component is a typical case. It receives an items prop and keeps a selection in state. When items changes, the selection may no longer make sense.
The common first attempt uses an Effect:
import { useState, useEffect } from 'react';
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selection, setSelection] = useState(null);
// Avoid: runs after render, so the screen shows a stale selection first.
useEffect(() => {
setSelection(null);
}, [items]);
const shown = isReverse ? [...items].reverse() : items;
return (
<>
<button onClick={() => setIsReverse(!isReverse)}>Reverse</button>
<ul>
{shown.map(item => (
<li
key={item.id}
onClick={() => setSelection(item)}
style={{ fontWeight: item === selection ? 'bold' : 'normal' }}
>
{item.title}
</li>
))}
</ul>
</>
);
}This works, but it is wasteful. Each time items changes, React renders the list with the old selection, commits that to the screen, runs the Effect, and then renders again. A key would reset isReverse too, which you do not want here.
The sequence of the extra render
Best option: store less state
Ask first whether you need to adjust state at all. Instead of storing the whole selected object, store only its ID and calculate the selected item during render:
import { useState } from 'react';
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selectedId, setSelectedId] = useState(null);
// Calculated during render. If the item is gone, selection is null.
const selection = items.find(item => item.id === selectedId) ?? null;
const shown = isReverse ? [...items].reverse() : items;
return (
<>
<button onClick={() => setIsReverse(!isReverse)}>Reverse</button>
<ul>
{shown.map(item => (
<li
key={item.id}
onClick={() => setSelectedId(item.id)}
style={{ fontWeight: item.id === selectedId ? 'bold' : 'normal' }}
>
{item.title}
</li>
))}
</ul>
</>
);
}There is nothing to adjust. If the selected item still exists in the new items, it stays selected. If it is gone, selection is null. This also removes the stale frame, because the value is correct in the same render.
Fallback: adjust state during render
Sometimes you cannot derive the value. In that case, you can set state while rendering, as long as it is the component's own state and you guard it with a condition. Keep the previous prop in state and compare:
import { useState } from 'react';
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selection, setSelection] = useState(null);
const [prevItems, setPrevItems] = useState(items);
if (items !== prevItems) {
setPrevItems(items);
setSelection(null);
}
// ...the rest of the component is unchanged
return null;
}React sees the state update during render, discards the output it just produced, and re-renders the same component right away. This happens before it renders children or commits to the DOM, so the user never sees the stale selection.
Choosing between the options
| Situation | Use |
|---|---|
| The value can be computed from props and other state | Calculate it during render |
| Everything in the component should start over | Give it a `key` |
| Only some state must change, and it cannot be derived | Compare with the previous prop and set state during render |
| The change is caused by something the user did | Update it in the event handler |
Try them in that order. The pattern with prevItems is the last resort. It adds a state variable and makes the data flow harder to follow.
Exercise
A Cart component receives a products prop and stores selectedProduct as a full object in state. After products refreshes, the old object is no longer in the list but is still highlighted. How would you fix this without an Effect?
Show answer
Store selectedId instead of the object, and calculate const selectedProduct = products.find(p => p.id === selectedId) ?? null during render. If the product is missing from the new list, the value is null in the same render and no adjustment or extra render pass is needed.