Ga naar de hoofdinhoud

Update nested state without mutation

Update a nested object in state by copying each object along the changed path.

react-basics5 min read

A form stores profile = { name, address: { city, country } }. Updating city mutates profile.address.city and then calls setProfile(profile). Copy the changed path: root object plus changed nested object Mutating a nested object keeps old references alive and can make React consumers miss the change. Identify the path The changed field is profile.address.city. The changed path runs through profile and address. Copy the nested object address: { ...profile.address, city: nextCity } This preserves country and replaces only the changed city. Copy the root object setProfile({ ...profile, address: nextAddress }) The root state value is also new, so React…

Read the full lesson

Sign up free: one personalized lesson every day, matched to your role and goals.

← Back to library

Neem contact op