Codementor Events

What is the purpose of the callback function as an argument of setState () in react?

Published May 24, 2021

Start writing here...The callback function is invoked when setState finished and the component gets rendered. Since setState is asynchronous the callback function is used for any post action. It is recommended to use the lifecycle method rather than this callback function.

setState({name: 'Amelia'}, () => console.log('The name has updated and component re-rendered'));

The setState callback is used to carry out operations in a React component after calling setState, like creating an AJAX request or throwing an error.

As a result, you can encounter situations where parts of your code execute before the state has had an opportunity to update.

We can use the setState function's callback to solve this particular React problem. Whatever we pass as the second argument to setState is executed after the setState function has updated.

This concludes the purpose of using callBack With setState in React

When not to use the callback

The docs recommend that you use the lifecycle events.

Here’s why.

PureComponent and shouldComponentUpdate can be used to tune up a component’s performance. They work by preventing lifecycle methods from firing when props and state haven’t changed.

The setState callback fires regardless of what shouldComponentUpdate returns. So, the setState callback will fire, even when the state hasn’t changed.

Don’t be afraid to use the setState callback. It’s there for a reason. But when you do, keep an eye on shouldComponentUpdate, if you see any shiftiness.

Discover and read more posts from Alicia Johnson
get started