Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to call a function once the state is updated in ReactJS

Introduction to ReactJS

Before we delve into the main topic of our discussion, it is crucial that we understand what ReactJS is and how it operates. ReactJS, commonly referred to as React, is a JavaScript library for building user interfaces, particularly for single-page applications. It allows developers to create reusable UI components. It was developed by Facebook to facilitate the creation of interactive, stateful & reusable UI components.

In layman terms, it's like a toolset full of different instruments like hammer, screwdriver, pliers etc., which you can use to build and shape your website, just like a carpenter would use his toolset to create furniture.

Understanding State in React

In React, "state" is an object that represents the parts of the app that can change. Each component can maintain its own state, which lives in an object called this.state.

Think of state as a data store that the component can read from at any time. For instance, in a weather app, the state might contain the current temperature and weather conditions. When the weather changes, the state is updated, and React knows to re-render the components that rely on that piece of state.

class Weather extends React.Component {
  state = {
    temperature: null,
    conditions: null
  };

  // rest of the component
}

In the example above, temperature and conditions are states of the Weather component.

Updating State

To update state in React, you use the setState method. This will merge the new state you provide with the old state, and then it will re-render the component.

this.setState({
  temperature: newTemperature,
  conditions: newConditions
});

In the example above, newTemperature and newConditions are the updated values for the state.

How to Call a Function Once State is Updated in React

Now let's get to the crux of the matter. In React, the setState function is asynchronous, which means it doesn't update the state immediately but schedules the update to the state object. Therefore, if you try to access the state after calling setState, you cannot be sure what it will be!

This is where the second callback function parameter to setState comes in. This function will not be invoked until setState is completed and the component is re-rendered.

this.setState({
  temperature: newTemperature,
  conditions: newConditions
}, () => {
  // This code will run after state is updated
  console.log(this.state.temperature, this.state.conditions);
});

In the example above, the console.log function will be called after the state is updated.

Why is this Useful?

There are many scenarios where it's useful to do something after state is updated. One common use case is when you want to manipulate the DOM or perform some computation that depends on the new state.

For instance, imagine we have a component that fetches some data from an API when the user clicks a button. We want to show a loading spinner while the data is being fetched. We can start showing the spinner by setting a loading state to true when the button is clicked, and then hide it once the data is ready.

Here's how we could do it:

class DataFetcher extends React.Component {
  state = {
    loading: false,
    data: null
  };

  fetchData = () => {
    this.setState({ loading: true }, () => {
      fetch('/api/data')
        .then(response => response.json())
        .then(data => this.setState({ data, loading: false }));
    });
  };

  // rest of the component
}

In the example above, we first set the loading state to true, and then we fetch the data. Once the data is ready, we update the state again, this time setting loading to false and data to the data we received. The spinner will show when loading is true and hide when loading is false.

Conclusion

As we've seen, the setState method in React is more powerful than it seems. By using the second callback function parameter, we can schedule code to run after the state update is applied and the component is re-rendered.

This allows us to handle complex scenarios, like showing and hiding a loading spinner, with ease. As long as we remember that setState is asynchronous and that we can't rely on the state immediately after calling setState, we can avoid bugs and ensure our components work as expected.

To put all of this in perspective, consider React as a diligent painter, who is continuously painting a scene (website) based on a set of instructions (state). Whenever the scene changes (state updates), the painter doesn't immediately start to modify the scene; instead, they smartly plan (schedule) their work. And if you've given them a follow-up task (callback function), they make sure to complete that once the scene is fully updated.