← Back to all snippets
JAVASCRIPT

Managing State with Functional Updates in useState

Learn to use the functional update form of React's useState hook. This prevents stale closures and ensures state updates are based on the latest value, crucial for reliable counters and toggles.

import React, { useState } from 'react';

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

  const increment = () => {
    // Using functional update to ensure 'count' is always the latest value
    setCount(prevCount => prevCount + 1);
  };

  const decrement = () => {
    setCount(prevCount => prevCount - 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

export default Counter;
How it works: This snippet demonstrates the best practice for updating state in React using the functional update form of `useState`. Instead of passing a direct value to `setCount`, we pass a function that receives the previous state (`prevCount`) as an argument. This ensures that when multiple state updates are batched or occur rapidly, each update correctly operates on the most recent state value, preventing common bugs related to stale closures and incorrect state calculations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs