Middle
Tell about the pattern of lifting state up in React.
sobes.tech AI
Answer from AI
The "lifting state up" pattern in React is used for sharing state between multiple components. Instead of each component having its own local state, the shared state is lifted to the nearest common parent component. This allows for data synchronization and centralized management.
For example, if two child components need to work with the same value, the state is stored in the parent, and the children receive it via props and can call functions to update the state.
Example:
function Parent() {
const [value, setValue] = React.useState('');
return (
<>
<Input value={value} onChange={e => setValue(e.target.value)} />
<Display value={value} />
</>
);
}
function Input({ value, onChange }) {
return <input value={value} onChange={onChange} />;
}
function Display({ value }) {
return <p>{value}</p>;
}
This approach simplifies state management and prevents data desynchronization between components.