React Hooks, Rerender & Keeping Same State - How It Works Underhood? July 30, 2023 Post a Comment 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<buttononClick={()=>setCount(count+1)} >{count}</button>Copyhere 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<buttononClick={()=>setCount(savedCount => savedCount+1)} >{count}</button>CopyHere savedCount is being passed from setCount to callback method and react internally maintains the current state of the hook. Share Post a Comment for "React Hooks, Rerender & Keeping Same State - How It Works Underhood?"
Post a Comment for "React Hooks, Rerender & Keeping Same State - How It Works Underhood?"