1

In my use case there are some controlled input components that stores data in states. When I change one of the dropdown input, it changes 3 more states and triggers an API call. How can I ensure that the 3 states are updated before making the API call ? I am using react functional component.

Hari haran
  • 23
  • 3

1 Answers1

1

Option 1

If you're using React 18 and you call those 3 setState(...) within the same function, those states are guaranteed to be updated in the next re-render thanks to automatic batching.

So in this case you can just use an useEffect on any of these 3 states, and call the API in that effect. Check this sandbox for a simple example.

Option 2

For people using React 17 or earlier, you still got auto batching, but only inside React event handlers (please refer to this awesome answer). If you're updating states outside React event handlers, the easiest way is, instead of useState three times, you just put those states in a single state in the first place to make sure they will be updated at the same time, because they are in the same state.

For example:

const [state, setState] = useState({
  state0: 0,
  state1: 'a',
  state2: true,
})

useEffect(() => {
  // Call API here
}, [state])
abemscac
  • 181
  • 5