Why doesn't useState function initialize state every time? Why doesn't useState function initialize state every time? reactjs reactjs

Why doesn't useState function initialize state every time?


useState as a function is storing the value you gave it within React's core. When the component re-renders, React is going to pass the updated count from its core to the component.

More information here.


State is initialized only once when you create the component, this is how React works. From the documentation:

What does calling useState do? It declares a “state variable”. Normally, variables “disappear” when the function exits but state variables are preserved by React.

Just to have the context here, let me summarize what is useState and how it works in more details.

What is useState:

So useState is a hook which helps you to handle state in a functional component.

How is it working?

Once you call useState you need to pass the initial value of the state what you would like to use in your functional component. It returns a pair of values the count and setCount.

So let's have your example below:

const [count, setCount] = useState(0);

So useState returned two items where count is the current value. And the second item, setCount is a function which can be used to update the value of the count state.

count can be used to represent the state for example the value in a div element:

return (   <div>{count}</div>)

In order to update the value you can achieve by calling setState(12).

From the docs you can read further here.


According to the React official website:

React keeps track of the currently rendering component. Thanks to the Roles of Hooks, we know that Hooks are only called from React components (or custom Hooks — which are also only called from React components).

There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.

Reference:

How does React associate Hook calls with components?