Skip to main content
InterviewHubPRO
Section Overview
Q348

Question 348 of 407

Part 9: React Hooks Deep Dive (262 - 316)

86%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

Why we need to pass a function to setState()?

mid LevelHooks

The reason behind for this is that setState() is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after setState() is called. That means you should not rely on the current state when calling setState() since you can't be sure what that state will be. The solution is to pass a function to setState(), with the previous state as an argument. By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of setState().

vbnet
Let's say the initial count value is