React  

Lifting State Up and component communication

Introduction

Lifting a state means moving it from a child component to its closest common parent so that multiple components can share and use the same data.

Core concept for Lifting State Up :

  •   State:  A container used to store data that can change over time based on UI.

  • Props: Used to pass data from parent to child components.

Why Lifting State Up is important

React follows a unidirectional data flow, meaning :

  • Data flows from parent to child via props.

  • Child components cannot directly modify the parent state.

When to Use Lifting State Up

  • Two or more components need the same data

  • One component needs to update the data used by another

For large applications, Redux or the Context API is preferred for managing global state.

When the state is lifted up, the child component becomes a controlled component, meaning its behavior is controlled by props rather than its own internal state.

Example

Step 1 : Create a Parent component

import Display from "./Display";
import Input from "./Input";
import { useState } from "react";

const Parent = ()=>{
        const [inputValue , setInputValue] = useState("");
    return (
        <>
        <Input inputValue = {inputValue} setInputValue = {setInputValue}/>
        <Display inputValue = {inputValue}/>
        </>
    )
}
export default Parent;

Create two child component like  input and display.

Step 2 : Create  Input Component

const Input = ({inputValue , setInputValue})=>{
    return (
        <>
            <input type="text" placeholder="Enter text " value={inputValue} 
                onChange={(e)=>setInputValue(e.target.value)}/>       
         </>
    )
}
export default Input;

Step 3 : Create Display component

const Display = ({inputValue})=>{
    return (
        <>
        <h2> Input is : {inputValue}</h2> 
        </>
    )
}
export default Display;

Step 4 : Import the parent component into App component

import Parent from './Component/Parent';

function App() {
  return (
    <div>
                    <Parent/>
              </div>
  );
}

export default App;

Output

lifting stateup

Conclusion

Lifting state up in React means moving state from a child component to a common parent component so that multiple components can share and use the same data.