38

Accessing React State right after setting it

 5 years ago
source link: https://www.tuicool.com/articles/hit/uyMfyiJ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Photo by Celso on Unsplash

As I have been browsing Stack Overflow questions, I’ve noticed that many bugs are due to trying to access a state value after setting it.

An example question on Stack Overflow.

I’ve stumbled many times for being unaware of setState being an asynchronous operation.

How do we access the state value right after setting it then?

:grimacing: Reproducing the Problem

Here is the code that shows accessing a state value ( clickCounts ) right after setting it synchronously.

And let’s see the logical error.

vMjiE3V.gif

console.log doesn’t have access to updated state value even though the call is made after setState .

:unamused:  Workaround (Not Recommended)

As setState is an operation, you can just wait till the value is set by React.

You might wait for a certain period to access the updated state using setTimeout .

NNvU3aV.gif

Tada :tada:. It works right?

Yes but No, at this point, you are just praying :pray: that setState finishes before accessing the state within setTimeout .

And also, you need to persist the event to be able to access event argument as shown in line#2 ( e.persist() ).

Refer to Event Pooling for e.persist.

:smile: Recommend Ways

There are two ways as mentioned in the official React documentation.

setState
componentDidUpdate

Let’s go over them both.

1. Using a callback passed to setState

setState has the following signature .

The callback is called after the state has updated using updater method thus the callback has access to the updated this.state .

Here is the updated code & the demo.

uUnEFbN.gif

2. Using componentDidUpdate life cycle method

React documentation “ generally recommends ” using componentDidUpdate .

I haven’t been able to find the reason for it, but my guess is because componentDidUpdate has access to the previous props and previous state (as well as being called before the callback as my demo shows).

Here is the code using componentDidUpdate .

And this demo shows that componentDidUpdate

  1. has the access to the updated state value.
  2. is called before the setState’s callback method.
r2q2ayB.gif

:wave: Parting Words

Frankly speaking, I’ve only used the callback to access updated value because I only found out about the recommended way of using componentDidUpdate while writing this blog :stuck_out_tongue_closed_eyes:.

And you can play around with the demo on CodeSandBox .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK