0
0
ReactHow-ToBeginner · 3 min read

How to Update State Based on Previous State in React

In React, to update state based on the previous state, use the functional form of setState by passing a function to it. This function receives the previous state as an argument, ensuring your update is based on the latest state value.
📐

Syntax

Use the functional update form of setState by passing a function that takes the previous state as input and returns the new state.

  • prevState: The current state value before update.
  • The function returns the updated state.
javascript
setState(prevState => {
  // return new state based on prevState
  return updatedState;
});
💻

Example

This example shows a counter that increments its value by 1 each time a button is clicked. It uses the functional update form to ensure the count updates correctly even if multiple clicks happen quickly.

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

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

  function increment() {
    setCount(prevCount => prevCount + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
Output
Count: 0 (initially) Count: 1 (after one click) Count: 2 (after two clicks)
⚠️

Common Pitfalls

Updating state directly without using the functional form can cause bugs when updates happen quickly or asynchronously. For example, using setCount(count + 1) inside an event handler may use a stale count value.

Always use the functional update form when new state depends on previous state.

javascript
/* Wrong way: may cause stale state updates */
setCount(count + 1);

/* Right way: uses previous state reliably */
setCount(prevCount => prevCount + 1);
📊

Quick Reference

ConceptUsageWhy Use It
Functional setStatesetState(prev => newState)Ensures update uses latest state
Direct setStatesetState(newState)May cause bugs if newState depends on old state
When to useWhen new state depends on previous stateAvoids stale or incorrect updates

Key Takeaways

Always use the functional form of setState when new state depends on previous state.
Pass a function to setState that receives the previous state and returns the updated state.
Avoid using direct state values in setState if the update depends on the current state.
Functional updates prevent bugs in asynchronous or rapid state changes.
This pattern works with useState hook in React functional components.