Skip to content Skip to sidebar Skip to footer

React Hooks, Rerender & Keeping Same State - How It Works Underhood?

How is it possible that following function after rerender keeps the current value? const Example = () => { const [count, setCount] = useState(0); return

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.


Post a Comment for "React Hooks, Rerender & Keeping Same State - How It Works Underhood?"