React basics 04 · State
Arrays, objects and shared state
Arrays and objects in state without mutations, shared state in the parent and how to arrange state so it doesn’t contradict itself.
Loading lesson…
React basics 04 · State
Arrays and objects in state without mutations, shared state in the parent and how to arrange state so it doesn’t contradict itself.
Loading lesson…
From lesson React basics 03 you know state with a single value: a number, a text, ticked/unticked. But real apps keep lists and objects in state – tasks, goods in a cart, a user's details. And that's where three new troubles start. You'll see the first one right away:
function TodoList() {const [todos, setTodos] = useState(['Shopping'])function add() {todos.push('Cleaning') // ❌ add a task to the array…setTodos(todos) // …and store it}return (<><button onClick={add}>Add</button><p>Tasks: {todos.length}</p></>)}
You click "Add" and the page still says "Tasks: 1". What's going on:
push adds the task to the existing array. Memory now holds ['Shopping', 'Cleaning'].setTodos(todos) gets the same array that's already in state. React compares the old and the new value, sees the same object and concludes nothing changed.That's the first trouble: arrays and objects in state aren't changed, they're replaced (section 1). The second comes when two components need the same data – a catalogue adds to the cart, the cart shows its contents. Where should the state live (section 2)? And the third when state grows: how to arrange it so it doesn't contradict itself (section 3).
Let's continue the comparison from the last lesson: state is a notebook React keeps for the cook. But this notebook is written in ink. Nothing in it gets rewritten or erased. When the task list should change, the old list isn't written over – a whole new entry is written, and React knows it should cook again because the entry is new.
Why did the push from the introduction render nothing? React recognises a change of state by comparing the old and the new value. For a number or a text that's clear. But for an object or an array it doesn't compare the content – only whether it's the same object (a reference from lesson JavaScript 09). A modified old object is still the same object, so React concludes nothing changed.
That's why you never change (mutate) state holding an object or an array; you create a new copy with the change – a new entry in the notebook written in ink. What for: only then does the change show on the page. When: every time state holds an array or an object.
// inside the TodoList component from the intro – state at the top, the handlers below it// <string[]> tells TypeScript the array will hold texts (lesson React basics 03)const [todos, setTodos] = useState<string[]>(['Shopping'])// ❌ push changes the EXISTING array – the setter gets the same object, React renders nothingfunction addWrong(text: string) {todos.push(text)setTodos(todos)}// ✅ a new array: the three dots (spread, lesson JavaScript 05) pour// the old items into it and the new one is added after themfunction addRight(text: string) {setTodos([...todos, text]) // ['Shopping'] → ['Shopping', 'Cleaning']}// in the component's JSX: <button onClick={() => addRight('Cleaning')}>Add</button>
For every common change there's a way of writing it that returns a new array or object. You know map and filter from lesson JavaScript 04, spread on arrays and toSorted from lesson JavaScript 05 and spread on objects from lesson JavaScript 03.
The table is an index: on the left what you want to do, in the middle the code that creates a new array or object, and on the right the method or assignment that would change the original – don't use those on state. In the examples:
todos is state with an array of todos, each todo an object { id, text, done },newTodo is a new todo you want to add, and id the id of the todo something should happen to,user is state with a user object, say { name: 'Anna', age: 30 },compare is a made-up compare function for sorting, say (a, b) => a.text.localeCompare(b.text) – it sorts the todos alphabetically.| I want to… | ✅ A new array / object | ❌ Changes the original |
|---|---|---|
| add at the end | setTodos([...todos, newTodo]) | push |
| add at the start | setTodos([newTodo, ...todos]) | unshift |
| remove by id | setTodos(todos.filter((t) => t.id !== id)) | splice |
| change one item | setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t))) | todo.done = … |
| change an object’s property | setUser({ ...user, name: 'Peter' }) | user.name = … |
| sort | setTodos(todos.toSorted(compare)) | sort |
The longest row – changing one item – taken apart step by step:
// in an event handler, say function toggle(id: number) { … } – id is the task that was clickedsetTodos(todos.map((t) => // go through all todos and make an item of the new array from each:t.id === id // is it the one that was clicked?? { ...t, done: !t.done } // yes → a new object: everything from the old one, just done flipped: t // no → the original todo unchanged))
Sometimes there's an object inside an object – say a person who has an address. You want to change just the city and keep everything else. Two attempts that suggest themselves don't work:
// person is state from useState:// person = { name: 'Anna', address: { city: 'London', street: 'Baker Street 1' } }// ❌ city is added to Anna, not to the address – spread sees only the outer levelsetPerson({ ...person, city: 'Boston' })// → { name: 'Anna', address: { city: 'London', street: 'Baker Street 1' }, city: 'Boston' }// ❌ the address is all new, but with just the city – the street is gonesetPerson({ ...person, address: { city: 'Boston' } })// → { name: 'Anna', address: { city: 'Boston' } }
Spread copies only one level – the outer object. It doesn't see into the inner object (that's why it's called a shallow copy). When something inside should change, you copy every level on the way to the change with spread: the outer object and the address.
// ✅ in an event handler (say after a click on "Move")setPerson({...person, // 1. a new outer object with all the propertiesaddress: { // 2. replace address with a new object:...person.address, // everything from the old address (street stays)city: 'Boston', // only the city is new},})// → { name: 'Anna', address: { city: 'Boston', street: 'Baker Street 1' } }
What you see: The object person in state, printed as text. The red button mutates (adds a tag with push), the others create new copies.
Try it:
The takeaway: A mutation doesn't show at once and pops up later in an unexpected place. A new copy always shows, and at once.
Loading the interactive part…
So far each component had its own notebook. What if two components need the same data? A goods catalogue adds to the cart, the cart shows what's in it. Let's first try what suggests itself – each of them keeps its own state:
// ❌ two notebooks – the catalogue writes, the cart knows nothing about itfunction Catalog() {const [cart, setCart] = useState<string[]>([]) // the catalogue's notebookreturn <button onClick={() => setCart([...cart, 'Apple'])}>Add an apple</button>}function Cart() {// [cart] = take just the value from the array useState returns, no setter needed hereconst [cart] = useState<string[]>([]) // the cart's notebook – a completely different onereturn <p>Items in the cart: {cart.length}</p> // still "0", however much you click}function Shop() {return (<><Catalog /><Cart /></>)}
Every call of useState sets up a notebook of its own, which belongs only to the component that called it. The apple is written into the catalogue's notebook and nobody wrote anything into the cart's. And there's no way around it: Cart can't look into another component's state, and Catalog can't send it props – props flow only from a parent to a child (lesson React basics 01), not between siblings.
The state moves one floor up, to the nearest common parent – this is called lifting state up. It takes four steps:
Catalog and Cart.Shop.useState into the parent. Delete the state from the children – now there's just one notebook.Cart gets the contents of the cart),Catalog gets the function "add to the cart"). You know a function as a value that someone else calls later from lesson JavaScript 02 – it's a callback.In the kitchen comparison: only the head chef has a notebook. The cooks at the stations have none. One gets a copy of the list of what's in the cart (data), the other gets the head chef's phone number and calls "add an apple" (a function). Only the head chef writes, so two lists can't drift apart.
// THE PARENT – keeps the single piece of state and passes it to the childrenfunction Shop() {const [cart, setCart] = useState<string[]>([]) // the names of the goods in the cart// the function that changes the state lives by the state – setCart is only at hand herefunction add(name: string) {setCart((prev) => [...prev, name]) // a new array with the added item}return (<>{/* a function goes down: you pass add without brackets, you don't call it (lesson React basics 03) */}<Catalog onAdd={add} />{/* data goes down: the contents of the cart */}<Cart items={cart} /></>)}// CHILD 1 – has no state. It gets the function onAdd and calls it on a clickfunction Catalog({ onAdd }: { onAdd: (name: string) => void }) {return <button onClick={() => onAdd('Apple')}>Add an apple</button>}// CHILD 2 – has no state, just shows the data from the parentfunction Cart({ items }: { items: string[] }) {return <p>Items in the cart: {items.length}</p>}
What happens after clicking "Add an apple":
Catalog calls onAdd('Apple'). It changes nothing itself – it just lets the parent know.onAdd is really the function add from the parent – the parent sent it there with onAdd={add}. So add('Apple') is called, and it writes a new array into the notebook.Shop renders again – and both children with it. Cart gets the new items and shows "Items in the cart: 1".When lifting state, what gets mixed up most often is what belongs to the parent and what to the child. The table sums it up: on the left a piece of code from the example, in the middle the component it belongs in, and on the right why it goes there.
| Piece of code | Where | Why there |
|---|---|---|
useState<string[]>([]) | the parent Shop | both children need it and Shop is the only one that has both below it |
the function add that changes the state | the parent, right below useState | setCart exists only in the parent; the rules for how the cart changes are in one place, by the state |
<Catalog onAdd={add} /> | the parent’s JSX | here the parent sends the child a function |
<Cart items={cart} /> | the parent’s JSX | here the parent sends the child data |
{ onAdd: (name: string) => void } | the child Catalog, at its parameter | the child describes what it needs to get to do its job |
onAdd('Apple') | the child Catalog, in the click handler | only the child knows when what was clicked |
items.length | the child Cart | the child just reads and shows its props |
In the props type of Catalog there's something new: instead of string or number there's a description of a function. Let's write it out with an interface, like ProfileCardProps in lesson React basics 01 – it does the same, it's just easier to read:
// the shape of the props of the component Cataloginterface CatalogProps {onAdd: (name: string) => void// onAdd the name of the prop – just like name in name: string// (name: string) what the function gets: one argument, a text// => separates "what it gets" from "what it returns"// void what it returns: nothing (void = emptiness)}function Catalog({ onAdd }: CatalogProps) {return <button onClick={() => onAdd('Apple')}>Add an apple</button>}
Such a description is called a function type or a function signature (in some other languages a prototype). It describes only the shape of the function – what arguments it takes and what it returns – not what it does inside. With it Catalog says: "send me any function I can give a text to". What the function does with it is the parent's business. In the symbol glossary of lesson TypeScript 01 it's just one row; here's what you need it for.
A few things that confuse:
=> comes the type of the result (void), not code.name in the type hints to the reader what's being sent. The function from the parent can name its parameter anything (add(item: string) would fit too) – TypeScript checks only the types.(id: number, quantity: number) => void takes two numbers, () => void takes nothing – say the prop onClose of a dialog that should just close.void almost always.What it's good for: TypeScript checks both sides by the description – the parent, what it sends into the prop, and the child, how it calls the function. It underlines a mistake in the editor before you even run the code:
// IN THE PARENT – what it sends into onAdd<Catalog onAdd={add} /> // ✅ add takes a text, fits the description<Catalog onAdd={(count: number) => {}} /> // ❌ error: this function wants a number, Catalog will give it a text<Catalog /> // ❌ error: the required prop onAdd is missing// IN THE CHILD – how it calls onAddonAdd('Apple') // ✅onAdd(42) // ❌ error: 42 isn't a textonAdd() // ❌ error: the argument is missing
What you see: Two fields, euros and dollars (1 € = 1.10 $). Both are controlled by the parent: it remembers only the amount and the currency it was entered in. The other field is calculated from that.
Try it:
CurrencyInput: it has no state, just value and onChange from the parent. The type (value: string) => void says: a function that gets a text and returns nothing.onChange is in CurrencyInput twice. On <input> it's the field's event – React gives it an object e. Inside it, the parent's onChange prop is called, and that gets just the text e.target.value. The prop has the same name as the field's event on purpose: whoever uses the component knows straight away what to expect from it.The takeaway: The two fields never contradict each other, because both read from one piece of state in the parent. If each had its own state, they'd have to watch each other.
Loading the interactive part…
The same data can be stored in state in different ways. Some arrangements allow nonsense combinations ("loading" and "error" at the same time), others don't. Four rules that save you a lot of bugs:
| ❌ Three booleans | ✅ One status |
|---|---|
|
|
On the left each of the three yes/no values can be true or false, so there are 2 × 2 × 2 = eight combinations. Only four make sense: nothing happening, loading, error, done. The other four ("loading and an error at the same time") shouldn't happen, but nothing in the code prevents them – it's enough to forget to switch off isLoading once.
On the right there's a single piece of state status and it always holds exactly one of four values: 'idle' (nothing is happening yet), 'loading', 'error' and 'done'. A nonsense combination can't be written. You know a type listing the options (a union) from lesson TypeScript 02: TypeScript makes sure you don't write anything else into status.
When you remember the selected item of a list, store only its id and find the item during render. A copy of the object wouldn't change along with the list:
// inside a component, above returnconst [fruits, setFruits] = useState(initialFruits) // initialFruits = a made-up array of fruit { id, name }// ❌ a copy of the object: when the fruit is renamed in the list, the old name stays here// const [selected, setSelected] = useState<Fruit | null>(null)// ✅ just the id (null = nothing selected)const [selectedId, setSelectedId] = useState<number | null>(null)// find the whole fruit on every render – always from the current listconst selected = fruits.find((f) => f.id === selectedId)// in the JSX: a button by every fruit that remembers just its id// <button onClick={() => setSelectedId(fruit.id)}>Select</button>// and the detail (&& from lesson React basics 01: shown only when something is selected):// {selected && <p>Selected: {selected.name}</p>}
Fruit in the "don't" line is a made-up fruit type. find (lesson JavaScript 04) returns the first fruit whose id matches, or undefined when there's none – which is also the case when nothing is selected.
What you see: A list of fruit. The Select button remembers the item twice: once as a copy of the object, once just as an id. At the bottom both details are side by side.
Try it:
The takeaway: A copy is a second record of the same data and drifts apart from the original. An id points to the one place where the data really lives – that is called a single source of truth.
Loading the interactive part…
When two values always change at the same time – say the x and y coordinates of a point on a picture – put them into one object. Then you can't end up changing just one of them:
// ❌ two pieces of state – on every change you have to think of bothconst [x, setX] = useState(0)const [y, setY] = useState(0)// ✅ one object – both coordinates are written at onceconst [position, setPosition] = useState({ x: 0, y: 0 })// in an event handler: a new object with both valuessetPosition({ x: 120, y: 40 })
When you then need to change just one of the values in the object, the recipe from section 1 applies: a new object with spread, setPosition({ ...position, x: 200 }).
// two versions of the same component – the parent uses it, say, as <Greeting name={userName} />// ❌ the prop copied into statefunction Greeting({ name }: { name: string }) {// [shownName] = take just the value from the array useState returns, no setter needed hereconst [shownName] = useState(name) // name is used only on the first renderreturn <p>Hello, {shownName}</p> // when the parent sends another name, the old one still shows}// ✅ the prop used directlyfunction Greeting({ name }: { name: string }) {return <p>Hello, {name}</p> // always the name the parent sent now}
useState uses the initial value only on the first render (lesson React basics 03). When the parent sends a new name, the component does render again, but useState now returns the value from the notebook – the first name. After that the state lives its own life and doesn't see changes to the props.
This section puts the lesson together into recipes to come back to when you write a list, a cart or anything with an array in state. You'll find the same pattern in the Cheat sheets on the React tab.
When you write your own app and run into one of these situations, the table tells you what to do about it and which section explains it. The situation on the left, the fix in the middle, the section on the right:
| Situation | What to do | Section |
|---|---|---|
| add, remove or change an item of an array in state | a new array (spread, filter, map) | 1 |
| change one property of an object in state | a new object (spread) | 1 |
| two components need the same data | state into the common parent | 2 |
| a child has to tell its parent something happened | a function in props (a callback) | 2 |
| several yes/no values that can contradict each other | one status | 3 |
| I remember the selected item | just its id | 3 |
// the file src/components/ItemList.tsximport { useState } from 'react'// 1. THE SHAPE OF AN ITEM – id never changes, so it serves as the key and for finding the iteminterface Item { id: number; text: string; done: boolean }export function ItemList() {// 2. STATE – only what can't be calculatedconst [items, setItems] = useState<Item[]>([]) // TypeScript can't tell the type from an empty arrayconst [text, setText] = useState('') // the text in the field for a new item// 3. CHANGES – each returns a NEW array (an updater, because it builds on the previous value)function add() {// a new array: the old items + the new one at the end; the new item's text is what's typed in the field// id: Date.now() returns the number of milliseconds since 1970 – so every new item gets a different numbersetItems((prev) => [...prev, { id: Date.now(), text, done: false }])setText('') // empty the field for the next item}function toggle(id: number) {// a new array: the clicked item as a copy with done flipped, the others unchanged (taken apart in section 1)setItems((prev) => prev.map((i) => (i.id === id ? { ...i, done: !i.done } : i)))}function remove(id: number) {// a new array: every item except the one with this idsetItems((prev) => prev.filter((i) => i.id !== id))}// 4. WHAT IS CALCULATED – it doesn't belong in state (lesson React basics 03)const left = items.filter((i) => !i.done).length // the number of unfinished items// 5. THE LOOKreturn (<>{/* a controlled field: shows the text from state and rewrites it after every letter */}<input value={text} onChange={(e) => setText(e.target.value)} /><button onClick={add}>Add</button> {/* pass the function, don't call it (lesson React basics 03) */}<ul>{items.map((i) => (<li key={i.id}> {/* key from a stable id */}<input type="checkbox" checked={i.done} onChange={() => toggle(i.id)} />{i.text}<button onClick={() => remove(i.id)}>✕</button> {/* an arrow: passes the id only on click */}</li>))}</ul><p>Left: {left}</p></>)}// use in a parent: <ItemList />
// THE PARENT – the nearest common parent of both children holds the single statefunction Parent() {const [value, setValue] = useState('') // one notebook for both childrenreturn (<>{/* down go the data and the function to change it. setValue can be passed as it is: it takesthe new text and returns nothing – exactly what Editor expects in onChange */}<Editor value={value} onChange={setValue} /><Preview value={value} /> {/* down go just the data */}</>)}// CHILD 1 – has no state of its own: shows value and reports a change to the parent through onChangefunction Editor({ value, onChange }: { value: string; onChange: (value: string) => void }) {return <input value={value} onChange={(e) => onChange(e.target.value)} />}// CHILD 2 – just shows the data from the parentfunction Preview({ value }: { value: string }) {return <p>{value}</p>}
What you want on the left, the code with an updater (a function that gets the previous value prev) on the right. These are the same recipes as in the table in section 1, just with an updater: each of these changes starts from the previous value, and then an updater is always safe (lesson React basics 03). In a simple click handler both forms would work.
With an object, notice the round brackets: (prev) => ({ ...prev, name: 'Peter' }). An arrow function that returns an object right away has to wrap it in brackets – otherwise JavaScript would take the { as the start of the function's body, not as an object (lesson JavaScript 02).
| I want to… | Code |
|---|---|
| add at the end | setItems((prev) => [...prev, item]) |
| add at the start | setItems((prev) => [item, ...prev]) |
| remove by id | setItems((prev) => prev.filter((i) => i.id !== id)) |
| change one item | setItems((prev) => prev.map((i) => (i.id === id ? { ...i, done: true } : i))) |
| sort | setItems((prev) => prev.toSorted(compare)) |
| change an object’s property | setUser((prev) => ({ ...prev, name: 'Peter' })) |
| change a nested property | setUser((prev) => ({ ...prev, address: { ...prev.address, city: 'Boston' } })) |
push, splice, sort or assignment item.done = ….Adding to an array and removing from it – always as a new array. The updater is ready; you fill in what it returns.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The first challenge practises section 1 (all three immutable operations) and calculated values from the last lesson, the second sections 1 and 2 (shared state in the parent). For every piece of state, first tell yourself: what I remember, where the state will live and what I just calculate. You'll find the recipes in section 4.
A classic on which you practise all three immutable operations: adding, changing and deleting. What exactly the list should do is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
The catalogue and the cart are siblings that need one notebook – the state must live in the parent. The cart stores only the productId and the quantity, not copies of the products (section 3).
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
filter, change an item = map with a copy of the object, sort = toSorted. For nested objects copy every level.