0
0
ReactHow-ToBeginner · 4 min read

How to Update Object in State React: Simple Guide

To update an object in React state, use the setState function with the spread operator to copy existing properties and overwrite the ones you want to change. For example, setState(prev => ({ ...prev, key: newValue })) safely updates the object without mutating the original state.
📐

Syntax

Use the setState function with a callback that receives the previous state. Inside, return a new object using the spread operator ... to copy existing properties, then specify the properties you want to update.

  • prev: previous state object
  • { ...prev }: copies all existing properties
  • key: newValue: updates or adds a property
javascript
setState(prev => ({
  ...prev,
  key: newValue
}))
💻

Example

This example shows a React component with an object in state. Clicking the button updates one property of the object without losing the others.

javascript
import React, { useState } from 'react';

function UserProfile() {
  const [user, setUser] = useState({ name: 'Alice', age: 25 });

  const updateAge = () => {
    setUser(prevUser => ({
      ...prevUser,
      age: prevUser.age + 1
    }));
  };

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={updateAge}>Increase Age</button>
    </div>
  );
}

export default UserProfile;
Output
Name: Alice Age: 25 [Click button] Name: Alice Age: 26
⚠️

Common Pitfalls

Common mistakes include mutating the state object directly, which can cause bugs and prevent React from re-rendering. Another mistake is forgetting to copy the existing properties, which leads to losing other data in the object.

Always create a new object with the spread operator instead of modifying the original.

javascript
/* Wrong: mutating state directly */
setUser(user.age = 30); // This does not work and is wrong

/* Wrong: replacing state without copying */
setUser({ age: 30 }); // This removes other properties like name

/* Right: copying and updating */
setUser(prevUser => ({ ...prevUser, age: 30 }));
📊

Quick Reference

  • Use setState(prev => ({ ...prev, key: value })) to update objects.
  • Never mutate state directly; always create a new object.
  • Use functional updates to avoid stale state issues.
  • Spread operator copies existing properties to keep them intact.

Key Takeaways

Always use the spread operator to copy existing object properties when updating state.
Use functional updates with setState to safely access the previous state.
Never mutate the state object directly to avoid bugs and ensure React re-renders.
Updating state with a new object triggers React to update the UI correctly.
Remember to include all existing properties when updating part of an object.