Data flow

In the last two chapters, we saw how to create single reusable components and how to compose them together effectively. Now, it is time to learn how to build a proper data flow for sharing data across multiple components in our application.

React enforces a very interesting pattern to make data go from the root to the leaves. This pattern is usually called unidirectional data flow, and we will look at it in detail in this section.

As the name suggests, in React, data flows in a single direction from the top to the bottom of the tree. This approach has many benefits because it simplifies the components' behavior and the relationship between components, making the code more predictable and maintainable.

Every component receives data from its parent in the form of props, and props cannot be modified. When the data is received, it can be transformed into new information and passed to the other children down the tree. Each of the children can hold a local state and use it as a prop for its nested components.

So far, we have only seen examples where the data is shared from parents to children components using props. However, what happens if a child has to push data up to its parent? Or what if a parent has to be updated when its children's state changes? Also, what if two sibling components need to share data? We will answer all of these questions with a real-world example.

We will start with a simple component that has no children, and we will transform it into a cleaner and structured component.

This approach will let us see the best patterns to apply in each phase to let the data flow across the tree.

Let's delve into the code for creating a Counter component, which starts from 0 and has two buttons: one for incrementing the value and one for decrementing it.

We will start by creating a class that extends the Component function from React:

  class Counter extends Component

The class has a constructor where the counter is initialized to 0, and the event handlers are bound to the component itself:

  constructor(props) { 
super(props);

this.state = {
counter: 0
};

this.handleDecrement = this.handleDecrement.bind(this);
this.handleIncrement = this.handleIncrement.bind(this);
}

The event handlers are simple, and they change the state, adding or removing a unit from the current counter:

  handleDecrement() { 
this.setState({
counter: this.state.counter - 1
});
}

handleIncrement() {
this.setState({
counter: this.state.counter + 1
});
}

Finally, inside the render method, the current value is displayed, and the buttons with their onClick handlers are defined:

  render() { 
return (
<div>
<h1>{this.state.counter}</h1>
<button onClick={this.handleDecrement}>-</button>
<button onClick={this.handleIncrement}>+</button>
</div>
);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.128.129