Reputation: 217
How is it possible that following function after rerender keeps the current value?
const Example = () => {
const [count, setCount] = useState(0);
return <button onClick={()=>setCount(count+1)} >{count}</button>
}
Logically looking:
Looking at the component as a clean function, this should work. But as I understand it, useState changes pure component into impure component.
But this still doesn't explain implementation of such a mechanism in an arrow function that does not have its own context. useState doesn't supposed to know which time in a row it's being called, if it's not hooked to parent function (like unique ID, this, callback, etc.)
React Hooks look like they break many paradigms of functional programming...
Upvotes: 3
Views: 2244
Reputation: 281696
Internally useState
keeps a track of whether the hooks is being initiated for he first time or not using a variable. If Its the first call to useState
it makes use of the passed argument else it maintains its own dispatchQueue
which it uses for updates.
As far as the below statement is concerned
<button onClick={()=>setCount(count+1)} >{count}</button>
here its not setCount that is preserving the variable, instead the arrow function inherits the count variable from the enclosing scope.
However, the setter from useState
hook does also specify a callback method to which it passes the current value. For example
<button onClick={()=>setCount(savedCount => savedCount+1)} >{count}</button>
Here savedCount
is being passed from setCount
to callback method and react internally maintains the current state of the hook.
Upvotes: 3