Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to update the data in ReactJS

1. Understanding Data in React

In the realm of ReactJS, one of the most essential topics is data. Think of data like the ingredients in a recipe. Each ingredient has its own role to play and contributes to the overall taste of the dish. Similarly, data in React components are like the ingredients that define the behavior of the components and contribute to the overall functionality of the application.

2. Two Types of Data - Props and State

React deals with two types of data - props and state. Props (short for properties) are like read-only ingredients. Once you've added them to the recipe, you can't change them. They are passed from the parent component to the child component and remain constant throughout the life of the component.

On the other hand, state is mutable. It's like the ingredients you can adjust according to taste while cooking. You can modify state data within the component based on user interactions or network changes.

3. An Intro to Updating Data

Now that we have a basic understanding of data in React, let's delve deeper into how to update this data. We'll primarily focus on updating the state as props are read-only and cannot be changed.

Imagine you're playing a game where you have to keep a count of the number of times you've clicked a button. This is a perfect scenario to understand the concept of updating data in React. The count is your state and with each click, you want to update this count.

4. The setState Method

In React, we use the setState method to update the state of a component. This method tells React that the component and its children need to be re-rendered with the updated state. Let's see how this works in our button clicking game example:

class ButtonClickGame extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          Click me!
        </button>
        <p>You've clicked the button {this.state.count} times.</p>
      </div>
    );
  }
}

In the above code, we're initializing our state in the constructor with a count set to 0. Then, we have a handleClick function which increments the count by 1 each time the button is clicked, using the setState method. The render method returns the button and a paragraph displaying the number of times the button has been clicked.

5. The Importance of setState

You may wonder why we can't just directly update the state like this.state.count = this.state.count + 1. The reason is that direct mutation of the state doesn't re-render the component. React's re-rendering process is tied to setState. When setState is called, React knows something has changed and it needs to re-render the component and possibly its children too.

6. The Role of the Virtual DOM

React maintains a virtual DOM, which is like a blueprint of the real DOM. When a state change occurs, React first updates the virtual DOM. Then, it compares the updated virtual DOM with the current real DOM, and makes the minimum number of changes necessary to make the real DOM look like the updated virtual DOM. This process, known as reconciliation, is what makes React so fast.

7. Asynchronous Nature of setState

One important thing to know is that setState is asynchronous. This means that it doesn't immediately update the state and re-render the component. Instead, React batches multiple setState calls and updates them all at once for performance reasons.

So if you are trying to access the updated state right after calling setState, you might not get the updated value. Instead, you can use a callback function with setState, which runs after the state has been updated:

this.setState({ count: this.state.count + 1 }, () => {
  console.log(this.state.count);
});

Here, the console.log is our callback function, which logs the updated count to the console.

Conclusion

Congratulations! You've just taken a significant stride in your ReactJS journey. Understanding how to update data is like learning how to adjust the heat when you're cooking. It's a key skill that affects the outcome of your dish (or in our case, the application). Remember, practice is the key to mastering this. So, go ahead, experiment with different recipes (read: applications) and flavors (read: data). Happy cooking with React!