Govur University Logo
--> --> --> -->
...

When you want to change a number in your app by adding to it, especially if you press the 'add' button many times very fast, why is it better to write `setNumber(oldNumber => oldNumber + 1)` instead of just `setNumber(currentNumber + 1)`?



When you call `setNumber`, you are using a state setter function provided by React's `useState` Hook to tell React to update a piece of your component's state. React state updates are asynchronous, meaning they don't happen immediately. Instead, React schedules these updates and often groups multiple updates together into a single re-render for performance, a process known as batching. This makes your application more efficient. When you write `setNumber(currentNumber + 1)`, the `currentNumber` inside that expression refers to the value of the state at the exact moment your component last rendered. It's a snapshot of the state value from that specific render cycle. If you press the 'add' button many times very ....

Log in to view the answer



Community Answers

Sign in to open profiles and full community answers.

No community answers yet. Be the first to submit one.

Redundant Elements