React state with objects and arrays
You pushed a song into an array in React state and the page didn't show it. See why in the first 30 seconds, and the fix. Then where the pushed song went (and why it shows up after a click on something unrelated), how to add, remove and sort with a new array, why sort() looks right and changes nothing, and the second bug: a copy that shares its objects, caught by an Undo button. It ends with the rule for which copies any change needs, and the answer to "why shouldn't you mutate state in React?".
In this lesson
Here’s a playlist called Road trip with three songs, a Play button, and three suggested songs with a plus beside each. Click the plus beside Glass Harbor. The code pushes the song into the state array, and the console says 4 songs in the playlist. The page still lists three.
So why does React ignore push? Because React never looked inside the array. When your code sets state, React asks one question: is this the same array I already have? push changed the array where it was, so it was the same array, and React ignored the update. Give React a new array that has the old songs and the new one, and the song appears.
But a new array is only the first step. This lesson also answers where the pushed song went, and shows a second bug behind this one that is harder to see. It covers what state holds, how to add, remove and sort without this bug, and how to change one song in the list. And it answers one question you may already have: why doesn’t React just look inside the array?
The code runs in a React project made with Vite (npm create vite@latest, then React and JavaScript), the same kind of project as the last lessons. JSX doesn’t run in plain JavaScript, so you need that build step. Each example replaces src/App.jsx. Two short examples are plain JavaScript, and those run in Node.
What state holds
This is the whole app with the bug:
import { useState } from 'react'
const SUGGESTED = [
{ id: 4, title: 'Glass Harbor', artist: 'Odessa Run' },
{ id: 5, title: 'Amber Lines', artist: 'The Lanterns' },
{ id: 6, title: 'Low Tide', artist: 'Mira Vale' },
]
export default function App() {
const [songs, setSongs] = useState([
{ id: 1, title: 'Night Bus', artist: 'The Lanterns' },
{ id: 2, title: 'Copper Sky', artist: 'June Arcade' },
{ id: 3, title: 'Slow Sunrise', artist: 'Mira Vale' },
])
const [playing, setPlaying] = useState(false)
function addSong(song) {
songs.push(song)
setSongs(songs)
console.log(songs.length + ' songs in the playlist')
}
return (
<main>
<h1>Road trip</h1>
<button onClick={() => setPlaying(!playing)}>{playing ? 'Pause' : 'Play'}</button>
<p className="count">{songs.length} songs</p>
<ol>
{songs.map((song) => (
<li key={song.id}>
{song.title} <small>{song.artist}</small>
</li>
))}
</ol>
<h2>Suggested</h2>
{SUGGESTED.map((song) => (
<button
key={song.id}
disabled={songs.some((added) => added.id === song.id)}
onClick={() => addSong(song)}
>
+ {song.title}
</button>
))}
</main>
)
}
The useState line makes an array of three songs. The array is one thing in memory. The variable songs does not contain it. It points at it, and that pointer is called a reference. React keeps a reference to the same array.
Now the click. songs.push(song) puts a fourth song inside that array, and setSongs(songs) gives React the reference it already has. Same array, so React ignores the update. A change made in place like this has a name: a mutation.
An object in state works the same way. Set one of its properties, and React gets the same object back:
const [settings, setSettings] = useState({ volume: 5, shuffle: false })
function volumeUp() {
settings.volume += 1
setSettings(settings)
}
Add that to the app with a Volume up button and a line that shows settings.volume, and a click leaves the page at Volume 5. This one, at least, your linter catches: the Oxlint setup Vite gives you warns that a value returned from useState() “cannot be modified”. It says nothing about songs.push(song).
Back to the playlist. Click the plus beside Amber Lines and Low Tide too. The console says 5 songs in the playlist, then 6 songs in the playlist, and the page still lists three. Then click Play. Play has its own state, true or false, and its code, setPlaying(!playing), doesn’t touch the songs. Guess how many songs the page shows now.
Six. Play gave React a new value, so React ran your component again. Your component read songs: the same array, which holds six songs by now. The page says 6 songs and lists Glass Harbor, Amber Lines and Low Tide under the first three.
So the change was not lost. It waited in memory until something made React run this component again. That’s why this bug looks random: the missing songs appear after a click on something unrelated. To watch it, put console.log('App ran, songs.length is ' + songs.length) under the useState lines. The console prints it when the page loads, prints nothing for the three plus clicks, and prints App ran, songs.length is 6 after Play. In development each line prints twice, because the Vite template wraps the app in Strict Mode.
A new array
So the rule is: don’t change the array React has. Make a new one. To add a song, write square brackets, and inside them three dots and songs, then the new song:
function addSong(song) {
setSongs([...songs, song])
}
The three dots put every song of the old array into the new one. They are called the spread syntax. Now the set function gets a different reference, React renders, and the song is on the page after one click: 4 songs, with Glass Harbor last and its plus button switched off.
To remove a song, use filter. It gives you a new array without the song you named, and the old array is not changed. Give each row a button that calls it:
function removeSong(id) {
setSongs(songs.filter((song) => song.id !== id))
}
<li key={song.id}>
{song.title} <small>{song.artist}</small>
<button aria-label={'Remove ' + song.title} onClick={() => removeSong(song.id)}>
×
</button>
</li>
Click the × on Copper Sky, and the page lists Night Bus and Slow Sunrise.
Be careful with sorting. Add a sort function above App, and a Sort A–Z button beside Play:
const byTitle = (a, b) => a.title.localeCompare(b.title)
function sortSongs() {
setSongs(songs.sort(byTitle))
}
<button onClick={sortSongs}>Sort A–Z</button>
sort returns an array, so this line looks right. But sort rearranges the array where it is, and then returns that same array. React gets the reference it already has, and the page keeps the old order: Night Bus, Copper Sky, Slow Sunrise. Click Play, and the sorted order shows up, the same bug as push.
JavaScript has a newer method for this, toSorted. It returns a sorted copy and does not change the original:
function sortSongs() {
setSongs(songs.toSorted(byTitle))
}
Click Sort A–Z, and the page lists Copper Sky, Night Bus, Slow Sunrise. toSorted has worked in every main browser since July 2023. In older code you’ll see [...songs].sort(byTitle), which copies first and then sorts the copy. That’s correct too.
You can see the difference in plain JavaScript. Save this as sort.mjs and run node sort.mjs:
const songs = [{ title: 'Night Bus' }, { title: 'Copper Sky' }, { title: 'Slow Sunrise' }]
const byTitle = (a, b) => a.title.localeCompare(b.title)
const titles = (list) => list.map((song) => song.title).join(', ')
const copy = songs.toSorted(byTitle)
console.log(copy === songs, '|', titles(copy), '|', titles(songs))
const sorted = songs.sort(byTitle)
console.log(sorted === songs, '|', titles(sorted), '|', titles(songs))
false | Copper Sky, Night Bus, Slow Sunrise | Night Bus, Copper Sky, Slow Sunrise
true | Copper Sky, Night Bus, Slow Sunrise | Copper Sky, Night Bus, Slow Sunrise
toSorted gave back a different array and left songs alone. sort gave back songs itself, now in a new order.
So put the array methods in two groups:
- Change the array they are called on:
push,splice,sort,reverse. - Give you a new array:
filter,map,toSorted, and the three dots,[...songs].
One step back
A new array for every change gives you something extra. The old array still exists, and nothing changed it. So add an Undo button. Before each change, the code keeps the current array in a second piece of state, and Undo puts that array back. The three handlers now call update:
const [previous, setPrevious] = useState(null)
function update(next) {
setPrevious(songs)
setSongs(next)
}
function undo() {
setSongs(previous)
setPrevious(null)
}
function addSong(song) {
update([...songs, song])
}
function removeSong(id) {
update(songs.filter((song) => song.id !== id))
}
function sortSongs() {
update(songs.toSorted(byTitle))
}
<button disabled={!previous} onClick={undo}>
Undo
</button>
Remove Copper Sky, click Undo, and the song is back. Undo is switched off again until the next change.
Now give each song a heart. Every song is an object with a property called liked, which is true or false. Here is the whole app with the heart:
import { useState } from 'react'
const SUGGESTED = [
{ id: 4, title: 'Glass Harbor', artist: 'Odessa Run', liked: false },
{ id: 5, title: 'Amber Lines', artist: 'The Lanterns', liked: false },
{ id: 6, title: 'Low Tide', artist: 'Mira Vale', liked: false },
]
const byTitle = (a, b) => a.title.localeCompare(b.title)
export default function App() {
const [songs, setSongs] = useState([
{ id: 1, title: 'Night Bus', artist: 'The Lanterns', liked: false },
{ id: 2, title: 'Copper Sky', artist: 'June Arcade', liked: false },
{ id: 3, title: 'Slow Sunrise', artist: 'Mira Vale', liked: false },
])
const [playing, setPlaying] = useState(false)
const [previous, setPrevious] = useState(null)
function update(next) {
setPrevious(songs)
setSongs(next)
}
function undo() {
setSongs(previous)
setPrevious(null)
}
function addSong(song) {
update([...songs, song])
}
function removeSong(id) {
update(songs.filter((song) => song.id !== id))
}
function sortSongs() {
update(songs.toSorted(byTitle))
}
function toggleLike(song) {
song.liked = !song.liked
update([...songs])
}
return (
<main>
<h1>Road trip</h1>
<button onClick={() => setPlaying(!playing)}>{playing ? 'Pause' : 'Play'}</button>
<button onClick={sortSongs}>Sort A–Z</button>
<button disabled={!previous} onClick={undo}>
Undo
</button>
<p className="count">{songs.length} songs</p>
<ol>
{songs.map((song) => (
<li key={song.id}>
{song.title} <small>{song.artist}</small>
<button aria-label={(song.liked ? 'Unlike ' : 'Like ') + song.title} onClick={() => toggleLike(song)}>
{song.liked ? '♥' : '♡'}
</button>
<button aria-label={'Remove ' + song.title} onClick={() => removeSong(song.id)}>
×
</button>
</li>
))}
</ol>
<h2>Suggested</h2>
{SUGGESTED.map((song) => (
<button
key={song.id}
disabled={songs.some((added) => added.id === song.id)}
onClick={() => addSong(song)}
>
+ {song.title}
</button>
))}
</main>
)
}
toggleLike changes the song’s liked property, then gives React a copied array. Click the heart on Night Bus, and it fills: ♥. Now click Undo. Guess what the heart does.
It stays filled. Undo did put the old array back, and Undo is switched off. But the three dots copied the array, not the songs. The old array and the new array point at the same three song objects, and the code changed one of them. It works the other way too: click the filled heart to empty it, click Undo, and the heart stays empty.
A copy that goes only one level deep is called a shallow copy. Node shows it in a few lines. Save this as shallow.mjs and run node shallow.mjs:
const songs = [
{ id: 1, title: 'Night Bus', liked: false },
{ id: 2, title: 'Copper Sky', liked: false },
]
const copy = [...songs]
console.log(copy === songs)
console.log(copy[0] === songs[0])
copy[0].liked = true
console.log(songs[0].liked)
false
true
true
A new array, the same first song, and a change made through the copy shows up in the original. So this time a new array was not enough.
What has to be new
The song has to be new too. map builds the new array. For the song that was clicked, it returns a new object: curly braces, and inside them three dots and the old song, to bring in its properties, then the liked property with the new value. Every other song goes into the new array unchanged. The handler now takes the song’s id:
function toggleLike(id) {
update(songs.map((song) => (song.id === id ? { ...song, liked: !song.liked } : song)))
}
<button aria-label={(song.liked ? 'Unlike ' : 'Like ') + song.title} onClick={() => toggleLike(song.id)}>
{song.liked ? '♥' : '♡'}
</button>
Click the heart on Night Bus, click Undo, and the heart is empty again.
Count what that change made: one new array and one new song. The other two songs are reused, so the copy is small. To check it, log what is new before calling update:
function toggleLike(id) {
const next = songs.map((song) => (song.id === id ? { ...song, liked: !song.liked } : song))
console.log('array is new: ' + !Object.is(next, songs) + ' ; songs that are new: ' + next.filter((song, i) => !Object.is(song, songs[i])).map((song) => song.title).join(', ') + ' ; songs reused: ' + next.filter((song, i) => Object.is(song, songs[i])).length)
update(next)
}
A click on Night Bus’s heart prints:
array is new: true ; songs that are new: Night Bus ; songs reused: 2
That is the rule for state of any depth: make a new copy of each object you pass through, going from the state down to the change, and reuse everything else. Put the playlist’s name and its songs in one object, and liking a song takes two copies, the playlist and its songs array, plus the new song:
import { useState } from 'react'
export default function App() {
const [playlist, setPlaylist] = useState({
name: 'Road trip',
songs: [
{ id: 1, title: 'Night Bus', artist: 'The Lanterns', liked: false },
{ id: 2, title: 'Copper Sky', artist: 'June Arcade', liked: false },
{ id: 3, title: 'Slow Sunrise', artist: 'Mira Vale', liked: false },
],
})
function toggleLike(id) {
setPlaylist({
...playlist,
songs: playlist.songs.map((song) => (song.id === id ? { ...song, liked: !song.liked } : song)),
})
}
function rename() {
setPlaylist({ ...playlist, name: 'Summer drive' })
}
return (
<main>
<h1>{playlist.name}</h1>
<button onClick={rename}>Rename</button>
<p className="count">{playlist.songs.length} songs</p>
<ol>
{playlist.songs.map((song) => (
<li key={song.id}>
{song.title} <small>{song.artist}</small>
<button aria-label={(song.liked ? 'Unlike ' : 'Like ') + song.title} onClick={() => toggleLike(song.id)}>
{song.liked ? '♥' : '♡'}
</button>
</li>
))}
</ol>
</main>
)
}
Like Night Bus, and its heart fills. Click Rename, and the heading says Summer drive with the heart still filled. Renaming copies only the playlist object: the songs array and all three songs are reused.
In deep state those copies get long. When that happens, make the state flatter, or use a library called Immer: you write the change as if you mutated, and Immer makes the copies. Install it with npm install immer, and the heart’s handler from the Undo app becomes:
import { produce } from 'immer'
function toggleLike(id) {
update(
produce(songs, (draft) => {
const song = draft.find((song) => song.id === id)
song.liked = !song.liked
}),
)
}
produce hands your function a draft of songs. It builds the new array and the new Night Bus from what you changed on the draft, and reuses the other two songs, the same copies the map version made. Like Night Bus, click Undo, and the heart is empty again.
Why not look inside?
Now the question from the start. Why doesn’t React just look inside the array?
Look at memory after a push. There is one array, and it holds four songs. React has no older array to compare it with, because your code changed the only one. React keeps a reference, not a copy. To see a change, React needs the old array and the new one, and after a mutation there is only one. A new array gives React both.
And the check stays small: two references, same or different, however long the playlist is. React makes that check with Object.is.
In an interview, the question is: why shouldn’t you mutate state in React? Two reasons:
- React compares references, not contents. A mutation keeps the reference, so React ignores the update.
- A mutation changes the old state too, which your code may still be using, as Undo was.
Making a copy and not changing the old state is called an immutable update.
In one line
React decides whether state changed by comparing references, so every change to an array or an object in state needs a new copy of each object on the path to the change, and nothing else. Now you can change an array or an object in state and say which copies the change needs and why. Next in this course: where state should live when two components need the same data.
Video transcript
Added, not shown
This button pushes a song into a state array in React, and the page doesn't show it. Click the plus beside Glass Harbor. The console says four songs in the playlist. The page still lists three. So why does React ignore push? Because React never looked inside the array. When your code sets state React asks one question. Is this the same array I already have? push changed the array where it was. So it was the same array and React ignored the update. Give React a new array that has the old songs and the new one, and the song appears. But a new array is only the first step. Where did the pushed song go? And there is a second bug behind this one that is harder to see. This video covers what state holds, how to add, remove and sort without this bug, and how to change one song in the list. And one question to think about on the way. Why doesn't React just look inside the array?
What state holds
Start with what state holds. The useState line makes an array of three songs. The array is one thing in memory. The variable songs does not contain it. It points at it, and that pointer is called a reference. React's reference points at that array too. Now the click. The push method puts a fourth song inside that array, and the set function gives React the reference it already has. Same array, so React ignores the update. A change made in place like this has a name: a mutation. An object is the same: set one of its properties, and React gets the same object back. Now add two more songs. The page still lists three. Then click Play. Play has its own state, true or false, and its code does not touch the songs. Guess how many songs the page shows now.
Six. Play gave React a new value, so React ran your component again. Your component read songs: the same array, which holds six songs by now. So the change is not lost. It waits in memory until something makes React run this component again. That's why this bug looks random: the missing songs appear after a click on something unrelated.
A new array
So the rule is: don't change the array React has. Make a new one. To add a song, write square brackets. Inside, three dots and songs: that puts every song of the old array into the new one. Then the new song. The three dots are called the spread syntax. Now the set function gets a different reference, React renders, and the song is on the page after one click. To remove a song, use the filter method. It gives you a new array without the song you named, and the old array is not changed. Be careful with sorting. The sort method returns an array, so this line looks right. But sort rearranges the array where it is, and then returns that same array. React gets the reference it already has, and the page keeps the old order. JavaScript has a newer method for this, named toSorted. It returns a sorted copy and does not change the original. So put the array methods in two groups. push, splice, sort and reverse change the array they are called on. filter, map and toSorted give you a new array, and so do the three dots.
One step back
A new array for every change gives you something extra. The old array still exists and nothing changed it. So add an Undo button. Before each change, the code keeps the current array in a second piece of state. Undo puts that array back. Remove a song, click Undo, and the song is back. Now give each song a heart. Every song is an object with a property called liked. It is true or false. Here is the heart's code. It changes the song's liked property, then gives React a copied array. Click the heart on Night Bus. It fills. Now click Undo. Guess what the heart does.
It stays filled. Undo did put the old array back. But the three dots copied the array, not the songs. The old array and the new array point at the same three songs. The code changed one of them. A copy that goes only one level deep is called a shallow copy. So this time a new array was not enough.
What has to be new
The song has to be new too. The map method builds the new array. For the song that was clicked, it returns a new object. Curly braces. Inside, three dots and the old song, to bring in its properties. Then the liked property with the new value. Every other song is put in the new array unchanged. Click the heart, click Undo, and the heart is empty again. Count what that change made. One new array and one new song. The other two songs are reused, so the copy is small. That is the rule for state of any depth: make a new copy of each object you pass through, going from the state down to the change, and reuse everything else. In deep state those copies get long. When that happens, make the state flatter, or use a library called Immer: you write the change as if you mutated, and Immer makes the copies.
Why not look inside?
Now the question from the start. Why doesn't React just look inside the array?
Look at memory after a push. There is one array, and it holds four songs. React has no older array to compare it with, because your code changed the only one. React keeps a reference, not a copy. To see a change, React needs the old array and the new one, and after a mutation there is only one. A new array gives React both. And the check stays small: two references, same or different, however long the playlist is. In an interview, the question is: why shouldn't you mutate state in React? Because React compares references, and does not compare contents. A mutation keeps the reference, so React ignores the update. And a mutation changes the old state too, which your code may still be using, as Undo was. Making a copy and not changing the old state is called an immutable update.
Next: where state lives
Now you can change an array or an object in state and say which copies the change needs and why. Next in this course: where state should live when two components need the same data. The next video is on screen now.

