"Lifting state up" is a technique used in React to share state between components.
It is necessary when multiple components need to access and/or modify the same state.
The process involves moving the shared state up to the closest common ancestor component.
This ancestor component then manages and passes down the state to its child components as props.
Child components can receive the shared state as props.
They can also receive functions from the parent to update the shared state.
Without Lifting State Up
With Lifting State Up
This way, instead of multiple components managing their own state copies.
The state is managed by a single component and passed down to other components.
Lifting state up promotes a unidirectional data flow.
Data flows down from the parent component to child components through props.
Any state updates are achieved by calling functions passed down from the parent component.
This makes the app more predictable and easier to debug.
Without Lifting State Up
// NameInput.js
import React, { useState } from 'react';
const NameInput = () => {
const [name, setName] = useState('');
return (
<div>
<label>
Name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
</div>
);
};
// AgeInput.js
import React, { useState } from 'react';
const AgeInput = () => {
const [age, setAge] = useState('');
return (
<div>
<label>
Age:
<input
type="number"
value={age}
onChange={(e) => setAge(e.target.value)}
/>
</label>
</div>
);
};
With Lifting State Up
// Parent.js
import React, { useState } from 'react';
const Parent = () => {
const [name, setName] = useState('');
const [age, setAge] = useState('');
const handleNameChange = (e) => {
setName(e.target.value);
};
const handleAgeChange = (e) => {
setAge(e.target.value);
};
return (
<div>
<NameInput name={name} onNameChange={handleNameChange} />
<AgeInput age={age} onAgeChange={handleAgeChange} />
</div>
);
};
// NameInput.js
const NameInput = ({ name, onNameChange }) => (
<div>
<label>
Name:
<input type="text" value={name} onChange={onNameChange} />
</label>
</div>
);
// AgeInput.js
const AgeInput = ({ age, onAgeChange }) => (
<div>
<label>
Age:
<input type="number" value={age} onChange={onAgeChange} />
</label>
</div>
);