React · Lesson 23 of 120
State with Objects
Copy, don't change.
State can hold an object. But you must never change the object directly. Instead, make a copy with the change, and set that. React notices the new object, and renders again.
- Objects in state
- Never change them
- Copy, then set
Updating a customer
Customer state holds a name and a city. The button sets a new object, copying everything with the spread operator, then replacing the city. We click it. Run it. The city changes, and the name is kept.
App.jsxjsx
import { useState } from "react";
export default function App() {
const [customer, setCustomer] = useState({ name: "Priya", city: "Leeds" });
function move() {
setCustomer({ ...customer, city: "York" });
}
return (
<div className="box">
<p>{customer.name} lives in {customer.city}</p>
<button id="move" onClick={move}>Move to York</button>
</div>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#move"}]Change or copy
Changing the city directly doesn't tell React anything, so the page doesn't update. Copying with spread, and setting the new object, updates the page every time.
Wrong
- customer.city = 'York'Same objectNo re-render
Right
- setCustomer({ ...customer, city })New objectRe-render
Summary
Never change state objects. Copy them with spread, change the copy, and set it. Next, state with arrays.
Key takeaways- { ...customer }
- New object
- Re-render
Next up: State with Arrays — add, remove, update