Flat Preloader Icon

Lifting State Up

“Lifting State Up” is a concept in React, a popular JavaScript library for building user interfaces, particularly when it comes to sharing state between components.

What is Lifting State Up?

In React, state refers to data that changes over time and drives the rendering of a component. Sometimes, multiple components need to share or synchronize state. When this happens, it’s common to “lift the state up” to the closest common ancestor of the components that need access to the state. This common ancestor then manages the state and passes it down to the child components via props.

When to Lift State Up?

  • Common State: When two or more components need to share the same state.
  • Synchronization: When the state in one component needs to reflect in another.
  • Complex Hierarchies: When managing state within deeply nested components becomes cumbersome.

How to Lift State Up?

  • Identify the Common Ancestor: Determine the closest common parent component of the components that need to share the state.
  • Move the State Up: Transfer the state and any state-changing logic to the common ancestor.
  • Pass State as Props: Pass the state and state-changing functions as props to the child components that need them.

Example

Suppose you have two sibling components that need to share a piece of state, count.
  1. Identify the Common Ancestor: Let’s say Parent is the common ancestor.
  2. Move the State Up: Move the count state to Parent.
  3. Pass State as Props: Pass count and a method to update count to the child components.
				
					import React, { useState } from 'react';

function Parent() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <ChildA count={count} setCount={setCount} />
      <ChildB count={count} setCount={setCount} />
    </div>
  );
}

function ChildA({ count, setCount }) {
  return (
    <div>
      <h2>Child A</h2>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment in Child A</button>
    </div>
  );
}

function ChildB({ count, setCount }) {
  return (
    <div>
      <h2>Child B</h2>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count - 1)}>Decrement in Child B</button>
    </div>
  );
}

export default Parent;

				
			

In this example:

  • The Parent component holds the state count and the function setCount.
  • The Parent component passes count and setCount to ChildA and ChildB as props.
  • ChildA and ChildB can now both read and update the count state, keeping them in sync.