React's useState hook is used to store a component's state values and update the UI through re-rendering when those values change.
useState causes the entire component to re-render, but it minimizes actual DOM changes by leveraging the Virtual DOM.
The internal implementation of useState is based on a linked list, which connects the currently rendering component and the hook to maintain state values and call different functions based on update events.
It's strange how the React community loves things with 'use' attached to them.
useServer, useCallback, useState, useMemo, etc.
Custom hooks also all have 'use' in their names.
Where did it all start?
useState is a famous hook.
It stores state values and re-renders when they change. It's pretty simple.
It's the example everyone knows.
It was mentioned that re-rendering occurs when the state value changes, but what's the scope of this re-rendering?
Just the p tag? Or the button tag as well?
The answer is the entire component where useState is called.
ExampleComponent is re-rendered, but
it's said that the virtual DOM is used to compare values and only modify the necessary parts of the DOM.
useState is called on every re-render. How are the values maintained?
The answer lies in the structure of useState.
This is the actual React useState code.
It fetches the dispatcher from the global object and then calls useState.
This doesn't help understand the structure.
Digging deeper, you find the following code.
It retrieves the hook, and directly binds the set function to the queue within the hook.
(bind binds 'this' to an existing function, uses the remaining arguments as the arguments of that function, and returns a new function with 'this' bound)
This doesn't help us figure out the reason.
Let's dig deeper.
You can see that the init value is assigned every time. This doesn't explain how the state is maintained.
Let's delve deeper. The hook seems suspicious.
currentlyRenderingFiber and workInProgressHook are global variables.
It seems to implement a linked list using assignment starting from the right.
So, if you were to examine the hook, it's expected to have the following structure.
Values are continuously added to the beginning.
The explanation is still unclear, so after looking at other useState implementations,
it was found that they don't all call mountState, but instead call updateState and rerenderState when re-rendering.
Therefore, the structure is as shown above, and different functions are called based on the event.
If you want to see the code directly, you can refer to react/packages/react-reconciler/src/ReactFiberHooks.js.