It explains useState hook pretty well. The component context is derived from the current execution context because react controls the render.
So calling useState() inside that render knows the context because react knows it's rendering that context at that time. Which is why useState() can only be used inside a function render.
Your version of using an index is correct, the implementation just uses different semantics akin to middleware:
instead of incrementing the index it resolves the next state though the next property chain.
(I'm guessing because it's faster to traverse a single next property than a long array while updating an index - might be just choice of semantics)
Thanks for the information, hope that helps as well.
Sorry for the delayed response. That was a good question and a great follow-up explanation. This is exactly right - each useState hook is called while React is rendering a particular component. React stores the memoized state from these calls as part of its in-memory representation of each component. Hopefully your explanation will be helpful to others who read this article in the future.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I'm trying to wrap my head around useState() working in multiple contexts. In a single context this works since the execution order is guaranteed.
useState() <-- state, setter at index 0
useState() <-- state, setter at index 1
But if you have not guaranteed execution order (many components and random renders) you can't count indexes.
How do you get useState() to keep a reference for your specific scope/context without supplying it with your context or a reference to save to.
Update:
Just read: medium.com/the-guild/under-the-hoo...
It explains useState hook pretty well. The component context is derived from the current execution context because react controls the render.
So calling useState() inside that render knows the context because react knows it's rendering that context at that time. Which is why useState() can only be used inside a function render.
Your version of using an index is correct, the implementation just uses different semantics akin to middleware:
instead of incrementing the index it resolves the next state though the next property chain.
(I'm guessing because it's faster to traverse a single next property than a long array while updating an index - might be just choice of semantics)
Thanks for the information, hope that helps as well.
Sorry for the delayed response. That was a good question and a great follow-up explanation. This is exactly right - each
useState
hook is called while React is rendering a particular component. React stores the memoized state from these calls as part of its in-memory representation of each component. Hopefully your explanation will be helpful to others who read this article in the future.