A callback function of setState in ReactJS

In this post, I am going to briefly explain how to use a callback function of the setState method. The behavior of the setState method seems simple but sometimes it is tricky because of its asynchronous nature.

There are plenty of questions on Stack Overflow about this method with code snippets similar to the below one.

class App extends Component {
    state = {
        name: "Default name"
    };

    changeName = newName => {
        this.setState({ name: newName });

        console.log(`Your name is ${this.state.name}`);
        // Output: "Your name is Default name"
    };
// ....

The output contains a un-updated state of the name variable. That’s because the setState method is asynchronous and you cannot assume that the state of a component will be updated immediately. The reasons for this behavior are clearly explained in the official documentation.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

ReactJS documentation

Fortunately, the solution to this problem is very simple.

changeName = newName => {
    this.setState(
        { name: newName },
        () => console.log(`Your name is ${this.state.name}`)
    );
};

The second parameter of the setState method is a callback function. It’s called when the state of the component is already updated. In this function, you can perform operations basing on the current state.

When I found out about this function, working with the component state became much easier for me. I hope it will also be helpful for you!

Leave a Reply

Your email address will not be published. Required fields are marked *