AceDevHub
Intermediate React Interview QuestionsIntermediatePractical

React · Question 37

How should you update objects and arrays stored in React state?

Direct answer

Create a new object or array that contains the desired changes instead of mutating the existing state value.

Profile.jsx
function Profile() {
  const [user, setUser] = useState({
    name: "Ava",
    skills: ["React"]
  });

  function addSkill() {
    setUser(current => ({
      ...current,
      skills: [...current.skills, "TypeScript"]
    }));
  }

  return <button onClick={addSkill}>{user.skills.length}</button>;
}
  • Objects: use object spread or another immutable transformation to create a new reference.
  • Arrays: prefer methods such as map, filter, concat, or spread instead of mutating methods such as push or splice on state.
  • Nested data: copy every changed level, or use an abstraction such as Immer if the state shape makes immutable updates cumbersome.