What is lifting state in React?

Hi, in this post we are going to learn about what is lifting state in React and we are going to see an example.

Lifting state in React is “A state that is lower in the tree and lifting it to the common parent component”

Example: we have 3 components

The <Name /> component:

Code:

import * as React from 'react'

function Name({name, onNameChange}) {
  return (
    <div>
      <label htmlFor="name">Name: </label>
      <input id="name" value={name} onChange={onNameChange} />
    </div>
  )
}

The <FavoriteAnimal /> component:

import * as React from 'react'

function FavoriteAnimal() {
  const [animal, setAnimal] = React.useState('')

  return (
    <div>
      <label htmlFor="animal">Favorite Animal: </label>
      <input
        id="animal"
        value={animal}
        onChange={event => setAnimal(event.target.value)}
      />
    </div>
  )
}

The <Display /> component:

The code:

import * as React from 'react'

function Display({name, animal}) {
  return <div>{`Hey ${name}, your favorite animal is: ${animal}!`}</div>
}

Then we have the App that is wrapping our 3 components:

import * as React from 'react'

function App() {
  const [name, setName] = React.useState('')

  return (
    <form>
      <Name name={name} onNameChange={event => setName(event.target.value)} />
      <FavoriteAnimal />
      <Display name={name} />
    </form>
  )
}

export default App

Now see how the <FavoriteAnimal /> and <Display /> components need the animal prop and this prop is inside the <FavoriteAnimal /> component code that means that isn’t possible to have access to that prop from other component, in this case <Display /> also is needing that prop.

So we are going to cut the animal prop (that is handled by a local state) that is inside <FavoriteAnimal /> code:

const [animal, setAnimal] = React.useState('')

And we are going to paste that local state (animal) inside the App component who is wrapping all the 3 components:

Then we need to pass that prop to <FavoriteAnimal /> component:

And also the <Display /> component (that is sibling of <FavoriteAnimal /> need the animal prop to work, so let’s pass that prop (name) on the <Display /> component as a prop too:

Is possible to access to the animal prop and be shared with others components because we are lifting (moving up) that state to the common parent component of those 3 components. In this case the common parent component is the App component.

View:

So lifting in React is “A state that is lower in the tree and lifting it to the common parent component”

By Cristina Rojas.