Lifting state up is a common pattern in React for sharing state between multiple components. When several components need to reflect the same changing data, it is recommended to lift the shared state up to their closest common ancestor. This allows you to manage state in one place and pass it down as props to the components that need it.
Here’s a step-by-step guide on how to lift state up in React:
Identify the common ancestor: Determine the closest common ancestor component that needs to manage the shared state.
Move the state to the common ancestor: Declare the state in the common ancestor component.
Pass the state down as props: Pass the state from the common ancestor to the child components that need it.
Pass the state updater function down as props: If child components need to update the state, pass the state updating function down to them as props.
Example: Simple Input and Display
Let’s create a simple React application where an input component updates a message, and the message is displayed in another component.
Step 1: Create the Common Ancestor Component
Let’s start by creating the common ancestor component, App
, which will hold the state.
import React, { useState } from 'react';
import MessageInput from './MessageInput';
import DisplayMessage from './DisplayMessage';
function App() {
const [message, setMessage] = useState('');
return (
<div>
<MessageInput message={message} onMessageChange={setMessage} />
<DisplayMessage message={message} />
</div>
);
}
export default App;
Step 2: Create the Input Component
The MessageInput
component will receive the message and the state updater function as props.
import React from 'react';
function MessageInput({ message, onMessageChange }) {
const handleChange = (e) => {
onMessageChange(e.target.value);
};
return (
<div>
<input type="text" value={message} onChange={handleChange} placeholder="Type a message" />
</div>
);
}
export default MessageInput;
Step 3: Create the Display Component
The DisplayMessage
component will receive the message as a prop and display it.
import React from 'react';
function DisplayMessage({ message }) {
return (
<div>
<p>{message}</p>
</div>
);
}
export default DisplayMessage;
Work Process:
- The
App
component holds the state for the message. - The
MessageInput
component receives the current message and a function to update it as props. When the input value changes, it calls theonMessageChange
function, which updates the state in theApp
component. - The
DisplayMessage
component receives the current message as a prop and displays it.
By lifting the state up to the App
component, both MessageInput
and DisplayMessage
can share the same state and remain synchronized.