What is lifting of State in react?🤔

Neville Kati N.
3 min readOct 20, 2022

--

So I have been working with React for quite a while, and it took me quite a while to grasp this concept of lifting state in React. This article is intended for React developers who also struggle with this lifting of state. Nonetheless, you will need to understand props and state in react.

Let us take a look at what it is together.

So there are times when some ‘sibling’ components (components with same direct parent component ) need to share some state data, but how can that be done in react 😕? This is what the concept of lifting state helps us accomplish.

Lifting of state is a concept that lets us define the state value of a component (e.g. component A ) in its closest parent component, and that state value is then passed down via props and used in that component A and any other sibling component. Hence, different components get to share the same state value. Make sense yet??🥴

NOTE: State can only be shared downwards in react. Not upwards nor sideways. That is why lifting of state is important. Will be much clearer in a bit

Let us take a look at an example 💪🏾.

We have a very basic React app with a button and 2 other components, and these components need to both display the number of times the button is clicked.

This is the structure of the app.

With the structure above, CompA and CompB are sibling components, and App is the parent component for both.

So we want CompA and CompB to record the number of times the button (mounted in the App component) is clicked. Hence, all of these components need to share the same state values.

Ideally using the concept of lifting of state, we need to;

  1. Define the state value in the App component.
  2. Pass the needed value as a prop value down to the other components (CompA and CompB) and use them.

By so doing, the App, CompA and CompB can all share the same state value.

fig: Using the prop value in CompA and CompB

OnClick of the button, the state value updates for both components.
Sweet!!🤗.

So that is about it for the lifting of state in React.
It’s nice to share this with you all.

Caio ✌🏻

Access the github repo here.

--

--

Neville Kati N.
Neville Kati N.

Written by Neville Kati N.

Next/React.js, Typescript developer lover of music, lover of people

No responses yet