React Updating Objects in State
Replace the changed path so earlier state snapshots remain trustworthy.
How it works
State can hold an object, but React does not make that object immutable for you. Mutating a nested field changes the old snapshot and can leave the view out of sync. Build a new outer record and a new changed nested record. Here a pickup location stays the same while its time changes. Use an updater because the new object is based on the latest state.
Run the code
Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.
No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.
Example
import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';
function App() {
const [loan, setLoan] = useState({
item: 'Market basket',
pickup: { desk: 'North', hour: '10:00' },
});
function move() {
setLoan((previous) => ({
...previous,
pickup: { ...previous.pickup, hour: '11:00' },
}));
}
return (
<main>
<h1>Neighbourhood lending desk</h1>
<p>
{loan.item} · {loan.pickup.desk}
</p>
<button onClick={move}>Move pickup to 11:00</button>
<output>Pickup: {loan.pickup.hour}</output>
</main>
);
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
);
Expected result
The pickup time becomes 11:00; the item and desk remain unchanged.
Spread copies the unchanged fields, while the explicit hour field wins at the changed level. This is a shallow-path update, not a deep clone of every object in the application. Keep related data together when it changes as one record, but avoid a giant state object that mixes unrelated concerns and makes every update difficult to read.
For API contracts and version differences, use React’s official documentation.