FrontendDeveloper.in

React question detail

What is an updater function? Should an updater function be used in all cases?

An updater function is a form of setState where you pass a function instead of a direct value. This function receives the previous state as an argument and returns the next state.

The updater function expression looks like below,

setCount(prevCount => prevCount + 1); // Safe and predictable

Here, prevCount => prevCount + 1 is the updater function.

In the React community, there's often a recommendation to use updater functions when updating state that depends on its previous value. This helps prevent unexpected behaviors that can arise from working with outdated or "stale" state.

While using an updater function is a good habit, it's not always necessary. In most cases, React batches updates and ensures that the state is up-to-date at the beginning of the event handler, so you typically don’t run into stale state issues during a single synchronous event. However, if you’re doing multiple updates to the same state variable within a single handler, using the updater form ensures that each update correctly uses the latest state value, rather than a potentially outdated one.

Example: Multiple Updates in One Handler

function handleCount() {
setCounter(a => a + 1);
setCounter(a => a + 1);
setCounter(a => a + 1);
}

In this example, a => a + 1 is an updater function. React queues these updater functions and applies them sequentially, each using the most recent state value. As a result, the counter will correctly increment by 3.

In many cases, such as setting state based on user input or assigning static values, you don’t need the updater function:

setName('Sudheer');
Back to all React questions
Get LinkedIn Premium at Rs 399