2. State lifting

cards.jsx

import React from 'react'

function Cards(props) {
  return (
    <>
    <h1> this component is inside card component</h1>
    {props.children}
    <button onClick={props.click}> {props.name}</button>
    </> 
  ) 
}
export default Cards

App.jsx

import { useState } from 'react'
import Cards from './components/cards'
import './App.css'

function App() {
  const [count, setCount] = useState(0)
  
  function onclickhandle() {
    setCount(count + 1)
  }
  
  return (
    <>
    <Cards name="click me" click={onclickhandle} >
        <h2>
          {count}
        </h2>
    </Cards>
      
    </>
  )
}
export default App

State Lifting in React

Definition:
State lifting means moving the state from a child component to a common parent component so the parent can manage and control the data, and pass it down to children via props.
In Your Code:
App.jsx:


How State Lifting Happens:


Purpose:


Summary:

State lifting is used to manage shared state at a higher level and coordinate state changes from child components using functions passed as props.


Hide show the data using button

App.jsx

import { use, useState } from 'react'
import './App.css'
import Panel from './components/Panel'

function App() {
  const [isactive,setisactive]=useState(false)

  function handleclick (){
    setisactive(isactive =>!isactive)
  }

  return (
    <>
      <div>
        <button onClick={handleclick}>{isactive ? "Hide":"show"}</button>
        <Panel isact={isactive}/>
      </div>
    </>
  )
}
export default App

Panel.jsx

import React from 'react'

const Panel = (props) => {
  return (
    <>
    <div>
        {props.isact ? <h1>Panel is active</h1> : <h1>Panel is not active</h1>}
    </div>
    </>
  )
}
export default Panel

Sums

color changer background

import { useEffect, useState } from 'react'
import './App.css'


function App() {
  const [bgcolor,setbgcolor] = useState("yellow")

  useEffect(() => {
    document.body.style.backgroundColor = bgcolor
  }, [bgcolor]) // run when bgColor changes

  function handleClick(e) {
    setbgcolor(e)
  }

  return (
    <>
      <div style={{display:'flex' ,padding:'20px',gap:'10rem'}}>
        <button onClick={(e)=>handleClick("red")}>Red</button>
        <button onClick={(e)=>handleClick("yellow")}>Yellow</button>
        <button onClick={(e)=>handleClick("green")}>Green</button>
        <button onClick={(e)=>handleClick("blue")}>Blue</button>
        <button onClick={(e)=>handleClick("black")}>Balck</button>
      </div>
    </>
  )
}
export default App


f


More

1. Passing props as children
3. UseEffect
4. Context API