REACT Tutorial



LIFTING STATE UP


Lifting State Up

In React, when multiple components need to share the same changing data, the best practice is to β€œlift the state up” to their closest common parent component. This means instead of each component maintaining its own state, you move the state to a higher-level component and pass it down as props.

Why lift state up?
To keep shared data in sync and avoid bugs caused by components having different versions of the same state.

Example: Sharing State Between Components

Suppose you have two sibling components that need to know whether a user is logged in. Instead of both maintaining separate states, you lift the state to their parent and pass it down.

function Parent() {
  const [isLoggedIn, setIsLoggedIn] = React.useState(false);

  return (
    <div>
      <LoginButton isLoggedIn={isLoggedIn} onLogin={() => setIsLoggedIn(true)} />
      <WelcomeMessage isLoggedIn={isLoggedIn} />
    </div>
  );
}

function LoginButton({ isLoggedIn, onLogin }) {
  return (
    <button onClick={onLogin}>
      { isLoggedIn ? 'Logout' : 'Login' }
    </button>
  );
}

function WelcomeMessage({ isLoggedIn }) {
  return (
    <h2>
      { isLoggedIn ? 'Welcome back!' : 'Please log in.' }
    </h2>
  );
}
  

The Parent component holds the isLoggedIn state and passes it to the two child components via props. The child components don't manage state themselves, which keeps the app’s data consistent.

Benefits of Lifting State Up

  • Keeps data synchronized across components
  • Makes your app easier to debug
  • Simplifies the flow of data and helps with maintainability
Remember: React apps work best with a clear, unidirectional data flow β€” lifting state up is a key technique for achieving this!

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review