Tyler Hawkins
1 min readAug 6, 2020

--

Hey Kitson, thanks for the question.

One thing to clarify real quick, my article doesn't say "not to access the state variable directly when updating state".

It says:

"The key here is that if your new state relies on the value of the old state, you should always use a function as the argument. If you are setting a value that does not rely on the value of the old state, then you can use a value as the argument."

That's the key principle to take away.

About the React docs, it drives me crazy that they have that example in there, because yes, that's a bad practice! Incrementing a counter is a perfect example of making a state update that relies on the previous state and should be done with a function. So maybe they wrote this example the way they did for the sake of simplicity.

It's interesting to note that they do in fact clarify this point later on in their docs in the Hooks API Reference and show how to update a counter properly:

https://reactjs.org/docs/hooks-reference.html#functional-updates

Hope that helps!

--

--

Tyler Hawkins
Tyler Hawkins

Written by Tyler Hawkins

Staff software engineer. Continuous learner. Educator. http://tylerhawkins.info

Responses (1)