3 ms·
I think a correction needs to be made in Part 2 "How Does State Change"[0]. The author says "Long story short, don’t expect state to be updated right away" in t
by konaraddi 6y ago
I think a correction needs to be made in Part 2 "How Does State Change"[0]. The author says "Long story short, don’t expect state to be updated right away" in the context of using `searchValue` right after calling `setSearchValue`. This gives the reader the impression that state is sometimes updated right away and sometimes not so we can't depend on it. However, it's impossible for a useState variable (e.g. `searchValue`) to be updated without a re-render [1]. Thus, using `searchValue` immediately after `setSearchValue` will always be outdated. So state is only updated after render.
[0] https://obedparla.com/code/a-visual-guide-to-react-mental-models-part-2-use-state-use-effect-and-lifecycles/#how-does-state-change https://obedparla.com/code/a-visual-guide-to-react-mental-mo...
[1] The `setSearchValue` updates a value that's outside (and captured) by the closure, React will re-render the component since setSearchValue was called (idk how this works behind the scenes and i think rendering is async), during the re-render `searchValue` and `setSearchValue` are assigned values again, and thus `searchValue` will finally be the updated value.
- obedm 6y agoYou're right, the code is not explained clearly enough. I intended it to be a "don't do this!" part, but I didn't really explain that. Great attention to detail, thank you for pointing it out, I'll update it!