How to Update State in React

This article provides a clear, step-by-step guide on how to update state in React. You will learn how to use the useState hook in functional components, how to perform safe updates when the new state depends on the previous state, and how to correctly update complex state types like objects and arrays without mutating the original data.

Updating State in Functional Components

In modern React, state is managed in functional components using the useState hook. When you call useState, it returns an array containing the current state value and a function to update that state.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

To update the state, you call the updater function (setCount in this example) with the new value. React will then schedule a re-render of the component with the updated state.

Updating State Based on Previous State

Because React state updates are batched and asynchronous, directly referencing the current state variable inside the updater function can sometimes lead to bugs if multiple updates occur quickly.

To safely update state based on its previous value, pass a function to the state updater. This function receives the previous state as its argument and returns the new state.

// Safe way to update state based on previous state
setCount(prevCount => prevCount + 1);

Updating Objects in State

In React, state should be treated as immutable. You should never modify an existing state object directly. Instead, you must create a new object that copies the existing properties and overrides the fields you want to change.

Use the JavaScript spread operator (...) to copy the properties of the existing object:

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

// Correct way to update an object
setUser(prevUser => ({
  ...prevUser,
  age: 26
}));

Updating Arrays in State

Just like objects, arrays in React state must be treated as immutable. Avoid using methods that mutate the original array, such as push(), pop(), shift(), or splice().

Instead, use non-mutating array methods like concat(), filter(), map(), or the spread operator.

Adding an Item to an Array

const [items, setItems] = useState(['Apple', 'Banana']);

// Correct way to add an item
setItems(prevItems => [...prevItems, 'Orange']);

Removing an Item from an Array

// Correct way to remove an item by filtering
setItems(prevItems => prevItems.filter(item => item !== 'Banana'));

Updating a Specific Item in an Array

// Correct way to update a specific item
setItems(prevItems => 
  prevItems.map(item => item === 'Apple' ? 'Green Apple' : item)
);