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.
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.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!