0
0
Reactframework~5 mins

Callback functions for state updates in React

Choose your learning style9 modes available
Introduction

Callback functions help update state based on the previous state safely. They avoid mistakes when many updates happen quickly.

When you want to increase a counter based on its current value.
When you need to toggle a boolean state like showing or hiding a menu.
When multiple state updates happen fast and you want to avoid wrong values.
When your new state depends on the old state value.
When you want to ensure state updates happen in the right order.
Syntax
React
setState(prevState => newState)

The callback receives the previous state as an argument.

Return the new state from the callback.

Examples
Increase a number state by 1 safely.
React
setCount(prevCount => prevCount + 1)
Toggle a boolean state from true to false or vice versa.
React
setIsOpen(prevIsOpen => !prevIsOpen)
Add a new item to an array state without losing old items.
React
setItems(prevItems => [...prevItems, newItem])
Sample Program

This component shows a number starting at 0. When you click the button, it uses a callback function to add 1 to the current count safely.

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

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick} aria-label="Increase count">Increase</button>
    </div>
  );
}

export default Counter;
OutputSuccess
Important Notes

Always use callback functions when new state depends on old state to avoid bugs.

React batches state updates, so direct state reads may be outdated inside event handlers.

Callback functions help React update state in the right order.

Summary

Callback functions receive previous state and return new state.

Use them when new state depends on old state.

They keep state updates safe and predictable.