Open In App

Explain the concept of “lifting up in React Hooks”

Lifting State Up” is a concept in React that involves moving the state of a component higher up in the component tree. In React, the state is typically managed within individual components, but there are situations where multiple components need to share and synchronize the same state. When this happens, you can lift the state to a common ancestor component that is higher in the component hierarchy.

Concept of Lifting State Up:

Example: Below is an example of lifting state up in React Hooks.




import React, {
    useState
} from 'react';
 
// Child component A
const CounterDisplay = ({ counter }) => {
    return <p>Counter: {counter}</p>;
};
 
// Child component B
const CounterButton = ({ onIncrement }) => {
    return <button
        onClick={onIncrement}>
        Increment Counter
    </button>;
};
 
// Parent component (common ancestor)
const App = () => {
    const [counter, setCounter] = useState(0);
    const handleIncrement = () => {
        setCounter(counter + 1);
    };
 
    return (
        <div>
            <CounterDisplay counter={counter} />
            <CounterButton
                onIncrement={handleIncrement} />
        </div>
    );
};
 
export default App;

Output:

Output

Article Tags :