Updating Objects in State·续1
function handleImageChange(e) { setPerson({ ...person, artwork: { ...person.artwork, image: e.target.value } }); }
return ( <> <label> Name: <input value={person.name} onChange={handleNameChange} /> </label> <label> Title: <input value={person.artwork.title} onChange={handleTitleChange} /> </label> <label> City: <input value={person.artwork.city} onChange={handleCityChange} /> </label> <label> Image: <input value={person.artwork.image} onChange={handleImageChange} /> </label> <p> <i>{person.artwork.title}</i> {' by '} {person.name} <br /> (located in {person.artwork.city}) </p> <img src={person.artwork.image} alt={person.artwork.title} /> </> ); }
```css
label { display: block; }
input { margin-left: 5px; margin-bottom: 5px; }
img { width: 200px; height: 200px; }
[!INFO]
Objects are not really nested
An object like this appears "nested" in code:
let obj = {
name: 'Niki de Saint Phalle',
artwork: {
title: 'Blue Nana',
city: 'Hamburg',
image: 'https://react.dev/images/docs/scientists/Sd1AgUOm.jpg',
}
};
However, "nesting" is an inaccurate way to think about how objects behave. When the code executes, there is no such thing as a "nested" object. You are really looking at two different objects:
let obj1 = {
title: 'Blue Nana',
city: 'Hamburg',
image: 'https://react.dev/images/docs/scientists/Sd1AgUOm.jpg',
};
let obj2 = {
name: 'Niki de Saint Phalle',
artwork: obj1
};
The
obj1object is not "inside"obj2. For example,obj3could "point" atobj1too:
let obj1 = {
title: 'Blue Nana',
city: 'Hamburg',
image: 'https://react.dev/images/docs/scientists/Sd1AgUOm.jpg',
};
let obj2 = {
name: 'Niki de Saint Phalle',
artwork: obj1
};
let obj3 = {
name: 'Copycat',
artwork: obj1
};
If you were to mutate
obj3.artwork.city, it would affect bothobj2.artwork.cityandobj1.city. This is becauseobj3.artwork,obj2.artwork, andobj1are the same object. This is difficult to see when you think of objects as "nested". Instead, they are separate objects "pointing" at each other with properties.
Write concise update logic with Immer
If your state is deeply nested, you might want to consider flattening it. But, if you don't want to change your state structure, you might prefer a shortcut to nested spreads. Immer is a popular library that lets you write using the convenient but mutating syntax and takes care of producing the copies for you. With Immer, the code you write looks like you are "breaking the rules" and mutating an object:
updatePerson(draft => {
draft.artwork.city = 'Lagos';
});
But unlike a regular mutation, it doesn't overwrite the past state!
[!INFO]
How does Immer work?
The
draftprovided by Immer is a special type of object, called a Proxy, that "records" what you do with it. This is why you can mutate it freely as much as you like! Under the hood, Immer figures out which parts of thedrafthave been changed, and produces a completely new object that contains your edits.
To try Immer:
- Run
npm install use-immerto add Immer as a dependency - Then replace
import { useState } from 'react'withimport { useImmer } from 'use-immer'
Here is the above example converted to Immer:
import { useImmer } from 'use-immer';
export default function Form() {
const [person, updatePerson] = useImmer({
name: 'Niki de Saint Phalle',
artwork: {
title: 'Blue Nana',
city: 'Hamburg',
image: 'https://react.dev/images/docs/scientists/Sd1AgUOm.jpg',
}
});
function handleNameChange(e) {
updatePerson(draft => {
draft.name = e.target.value;
});
}
function handleTitleChange(e) {
updatePerson(draft => {
draft.artwork.title = e.target.value;
});
}
function handleCityChange(e) {
updatePerson(draft => {
draft.artwork.city = e.target.value;
});
}
function handleImageChange(e) {
updatePerson(draft => {
draft.artwork.image = e.target.value;
});
}
return (
<>
<label>
Name:
<input
value={person.name}
onChange={handleNameChange}
/>
</label>
<label>
Title:
<input
value={person.artwork.title}
onChange={handleTitleChange}
/>
</label>
<label>
City:
<input
value={person.artwork.city}
onChange={handleCityChange}
/>
</label>
<label>
Image:
<input
value={person.artwork.image}
onChange={handleImageChange}
/>
</label>
<p>
<i>{person.artwork.title}</i>
{' by '}
{person.name}
<br />
(located in {person.artwork.city})
</p>
<img
src={person.artwork.image}
alt={person.artwork.title}
/>
</>
);
}
```json package.json { "dependencies": { "immer": "1.7.3", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "use-immer": "0.5.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
```css
label { display: block; }
input { margin-left: 5px; margin-bottom: 5px; }
img { width: 200px; height: 200px; }
Notice how much more concise the event handlers have become. You can mix and match useState and useImmer in a single component as much as you like. Immer is a great way to keep the update handlers concise, especially if there's nesting in your state, and copying objects leads to repetitive code.
[!INFO]
Why is mutating state not recommended in React?
There are a few reasons:
- Debugging: If you use
console.logand don't mutate state, your past logs won't get clobbered by the more recent state changes. So you can clearly see how state has changed between renders.- Optimizations: Common React optimization strategies rely on skipping work if previous props or state are the same as the next ones. If you never mutate state, it is very fast to check whether there were any changes. If
prevObj === obj, you can be sure that nothing could have changed inside of it.- New Features: The new React features we're building rely on state being treated like a snapshot. If you're mutating past versions of state, that may prevent you from using the new features.
- Requirement Changes: Some application features, like implementing Undo/Redo, showing a history of changes, or letting the user reset a form to earlier values, are easier to do when nothing is mutated. This is because you can keep past copies of state in memory, and reuse them when appropriate. If you start with a mutative approach, features like this can be difficult to add later on.
- Simpler Implementation: Because React does not rely on mutation, it does not need to do anything special with your objects. It does not need to hijack their properties, always wrap them into Proxies, or do other work at initialization as many "reactive" solutions do. This is also why React lets you put any object into state--no matter how large--without additional performance or correctness pitfalls.
In practice, you can often "get away" with mutating state in React, but we strongly advise you not to do that so that you can use new React features developed with this approach in mind. Future contributors and perhaps even your future self will thank you!
- Treat all state in React as immutable.
- When you store objects in state, mutating them will not trigger renders and will change the state in previous render "snapshots".
- Instead of mutating an object, create a new version of it, and trigger a re-render by setting state to it.
- You can use the
{...obj, something: 'newValue'}object spread syntax to create copies of objects. - Spread syntax is shallow: it only copies one level deep.
- To update a nested object, you need to create copies all the way up from the place you're updating.
- To reduce repetitive copying code, use Immer.
Fix incorrect state updates
This form has a few bugs. Click the button that increases the score a few times. Notice that it does not increase. Then edit the first name, and notice that the score has suddenly "caught up" with your changes. Finally, edit the last name, and notice that the score has disappeared completely.
Your task is to fix all of these bugs. As you fix them, explain why each of them happens.
```js {expectedErrors: {'react-compiler': [11]}} import { useState } from 'react';
export default function Scoreboard() { const [player, setPlayer] = useState({ firstName: 'Ranjani', lastName: 'Shettar', score: 10, });
function handlePlusClick() { player.score++; }
function handleFirstNameChange(e) { setPlayer({ ...player, firstName: e.target.value, }); }
function handleLastNameChange(e) { setPlayer({ lastName: e.target.value }); }
return ( <> <label> Score: <b>{player.score}</b> {' '} <button onClick={handlePlusClick}> +1 </button> </label> <label> First name: <input value={player.firstName} onChange={handleFirstNameChange} /> </label> <label> Last name: <input value={player.lastName} onChange={handleLastNameChange} /> </label> </> ); }
```css
label { display: block; margin-bottom: 10px; }
input { margin-left: 5px; margin-bottom: 5px; }
Here is a version with both bugs fixed:
import { useState } from 'react';
export default function Scoreboard() {
const [player, setPlayer] = useState({
firstName: 'Ranjani',
lastName: 'Shettar',
score: 10,
});
function handlePlusClick() {
setPlayer({
...player,
score: player.score + 1,
});
}
function handleFirstNameChange(e) {
setPlayer({
...player,
firstName: e.target.value,
});
}
function handleLastNameChange(e) {
setPlayer({
...player,
lastName: e.target.value
});
}
return (
<>
<label>
Score: <b>{player.score}</b>
{' '}
<button onClick={handlePlusClick}>
+1
</button>
</label>
<label>
First name:
<input
value={player.firstName}
onChange={handleFirstNameChange}
/>
</label>
<label>
Last name:
<input
value={player.lastName}
onChange={handleLastNameChange}
/>
</label>
</>
);
}
label { display: block; }
input { margin-left: 5px; margin-bottom: 5px; }
The problem with handlePlusClick was that it mutated the player object. As a result, React did not know that there's a reason to re-render, and did not update the score on the screen. This is why, when you edited the first name, the state got updated, triggering a re-render which also updated the score on the screen.
The problem with handleLastNameChange was that it did not copy the existing ...player fields into the new object. This is why the score got lost after you edited the last name.
Find and fix the mutation
There is a draggable box on a static background. You can change the box's color using the select input.
But there is a bug. If you move the box first, and then change its color, the background (which isn't supposed to move!) will "jump" to the box position. But this should not happen: the Background's position prop is set to initialPosition, which is { x: 0, y: 0 }. Why is the background moving after the color change?
Find the bug and fix it.
If something unexpected changes, there is a mutation. Find the mutation in App.js and fix it.
```js {expectedErrors: {'react-compiler': [17]}} src/App.js import { useState } from 'react'; import Background from './Background.js'; import Box from './Box.js';
