Sharing state between two or more components in React

Eric Njanga Dec 28, 2017

Lifting state up

In React, sharing state between components can only be done by moving it up to the closest common ancestor of the components that need it. We call it “lifting state up”.

Lifting state involves writing more “boilerplate” code than two-way binding approaches (AngularJS for instance), but as a benefit, it takes less work to find and isolate bugs. Since each component has it private state (non accessible anywhere outside that component), the surface area for bugs is greatly reduced.

What’s important to remember

There should be a single “source of truth” for any data that changes in a React application. When desirous of sharing the state among components, we should lift it up to their closest common ancestor and rely on a top-down data flow (a component passes it state down as props to its children components).

© 2018 Copyright Eric Njanga | |