Skip to content
Advertisement

Using callback function instead of state when changing state’s value in react

Why we need to use callback function instead of state value in react when setting state to the new value?

Advertisement

Answer

The callback function should be used if you are relying on previous state, for example: setState(prevState => prevState + 5)

You have to do it this way because React may batch multiple setState() calls into a single update for performance. It means that the value that you get from state directly might not be updated yet, so you will run into a bug. But the state value that you get as a parameter in setState callback is always correct. It is described very well here in react docs: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement