DEV Community

Discussion on: Synchronous State With React Hooks

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

You're not wrong. But the reply is also a bit narrow in scope (probably because the examples I gave were purposely over-simplified, to avoid making it a code-specific case study).

On one level, sure, we should always strive to utilize state in a manner consistent with your description. On another level, I think it's a bit naïve to imagine that we can always do that. For example, there are times when the validation logic is sufficiently complex that I absolutely don't want for it to run at render time. Because if you run it at render time, that means it's going to run on every re-render.

Of course, you make a good reference to useMemo(). A tool like that can take the sting out of running something repeatedly on render. Admittedly, I need to get more comfortable with that valuable tool.

But I guess the deeper, simplified issue is this:

Setting a state variable feels very similar to setting any other type of variable. Yeah, we know that it triggers some very different stuff in the background. But it's extremely common, in any language or style of coding, to set a variable on one line, and then, a handful of microseconds later, in some other block of code, check on the value in that same variable.

So the question becomes, if you have a scenario in React where you've set a state variable on one line, and then, a handful of microseconds later, in some other block of code, you need to check on the value in that same variable, how do you do that? As I've tried to point out in this article, the answer to that question can be quite tricky.

Collapse
 
tbroyer profile image
Thomas Broyer

So the question becomes, if you have a scenario in React where you've set a state variable on one line, and then, a handful of microseconds later, in some other block of code, you need to check on the value in that same variable, how do you do that?

Well, I would say you try hard not to get into that situation. And I believe there are ways to avoid that situation that would also be more idiomatic; by thinking differently about your problem.

I think the crux is to definitely stop thinking about events and "when you set X" or "when you change state".

If you need to compute state that depends on other state, then try storing coarser values into state (your whole form as one object) and pass a function to the state setter, or deriving at rendering time and memoizing.