How is it possible that following function after rerender keeps the current value? const Example = () => { const [count, setCount] = useState(0); return
Solution 1:
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 >
Copy
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 >
Copy
Here savedCount is being passed from setCount to callback method and react internally maintains the current state of the hook.
Post a Comment for "React Hooks, Rerender & Keeping Same State - How It Works Underhood?"