I know that in React class components React uses the "this" binding to "track" props and state. In hooks it is achieved thanks to closures, is my doubt?
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count 1)}>
Click me
</button>
</div>
);
}
This code works as you would expect a counter, if you were using class component you would have to use setState() in callback mode to access the previous state, but in hooks how does the magic happen?
are there any bindings on the hooks or not?
CodePudding user response:
React keeps track of state by internally counting the number of times useState
is called the first time a component mounts. The value passed into useState
is then set into React's internal state. For example, given
const Component = () => {
const [state1, setState1] = useState('one');
const [state2, setState2] = useState('two');
return 'foo';
};
React will then have the following state stored internally:
['one', 'two']
with one item in the (hidden, internal) state array for each call of useState
that there is.
When a state setter is called, the corresponding item in the internal state array will be updated, and then the component will re-render. When a component re-renders, each useState
call then returns the appropriate item in the internal state array. The first useState
call will return the first item in the internal state array, the second useState
call will return the second item, and so on.
In your code, with hooks, the click handler has a closure over the value of count
that existed at that particular render of Counter.
if you were using class component you would have to use setState() in callback mode to access the previous state
Not really - if this code was a class component, it would be free to reference this.state.count
directly without using the callback version.