An example of the issue is found on CodeSandBox. Am I short circuiting myself between TRUE/FALSE values?
Can someone please help explain why the state variable isOptionOne
is not being set as expected? Upon calling setIsOptionOne
I would think that I can use isOptionOne
in the remaining lines of code of the function. Unfortunately, that does not seem to be the case. To verify, see the console.log
output. The two values for isDefault
and isOptionOne
should match.
Where am I going wrong? Thank you.
CodePudding user response:
That is the expected behavior. React batches the state updates, which means it doesn't immediately update the state and re-render everything after each setState
method call. From official documentation:
setState
() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.Think of
setState
() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
setState
() does not always immediately update the component. It may batch or defer the update until later. This makes readingthis.state
right after callingsetState
() a potential pitfall. Instead, usecomponentDidUpdate
or asetState
callback (setState(updater, callback)
), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.
Additionally, the above document is for the traditional class component's setState
API. If you want to detect a change in your hook-based state, use useEffect
.