Sub topic 12
Choosing a good state shape
This chapter assumes you can declare state with useState, update objects and arrays without mutating them, and pass props between components. It covers how to organize state so that it is hard to get wrong.
Why shape matters
Every extra piece of state is something you must keep consistent. A good shape makes bugs impossible to express, because invalid combinations of values cannot exist. Four rules cover most cases.
Group state that changes together
If two values always update at the same time, store them as one object. Separate x and y variables for a pointer position are an example. Group them as { x, y } so that one setter call updates both.
Avoid contradictory state
Boolean flags often allow combinations that make no sense. In this form, nothing stops isSending and isSent from both being true:
const [isSending, setIsSending] = useState(false);
const [isSent, setIsSent] = useState(false);Replace the flags with one state variable that holds a single status:
import { useState } from 'react';
function Feedback() {
const [status, setStatus] = useState('typing'); // 'typing' | 'sending' | 'sent'
function handleSend() {
setStatus('sending');
setTimeout(() => setStatus('sent'), 1000);
}
if (status === 'sent') return <p>Thanks!</p>;
return (
<button onClick={handleSend} disabled={status === 'sending'}>
{status === 'sending' ? 'Sending...' : 'Send'}
</button>
);
}The component can now be in only one status at a time.
Avoid redundant and duplicated state
Do not store a value you can calculate from other state. If you keep firstName, lastName, and fullName, you must update all three, and one of them will eventually be stale. Keep the first two and compute the third during render. The next chapter covers this technique in detail.
Duplication is a related problem. Storing a copy of an object in a second state variable creates two sources of truth. Here the copy goes stale when the list changes:
const [items, setItems] = useState(initialItems);
const [selectedItem, setSelectedItem] = useState(items[0]); // a copyStore the identifier instead, then look up the object:
import { useState } from 'react';
const initialItems = [
{ id: 1, title: 'pretzels' },
{ id: 2, title: 'crispy seaweed' },
];
function Menu() {
const [items, setItems] = useState(initialItems);
const [selectedId, setSelectedId] = useState(1);
const selectedItem = items.find(item => item.id === selectedId);
function rename(id, title) {
setItems(items.map(i => (i.id === id ? { ...i, title } : i)));
}
return (
<>
<p>Selected: {selectedItem.title}</p>
{items.map(item => (
<div key={item.id}>
<input value={item.title} onChange={e => rename(item.id, e.target.value)} />
<button onClick={() => setSelectedId(item.id)}>Choose</button>
</div>
))}
</>
);
}Renaming an item now updates the selected label automatically, because selectedItem is looked up from items on every render.
Avoid deeply nested state
Updating a value three levels deep needs a spread at every level. If you find yourself writing that, flatten the data. Keep a flat array or an object keyed by id, and store relationships as ids.
callout tipPlaceholder removed below.