19) Lifting state up
Why we need
Lifting State Up is a core pattern in React used when multiple components need to share the same state.
Instead of keeping state in each child, you move (lift) the state to their closest common parent, and pass it down via props.
Steps to use this pattern,
i) Move state from child → parent
ii) Pass data down as props
iii) Pass functions down to update stateExample
import { useState } from "react"; const Parent = () => { const [text, setText] = useState(""); return ( <div> <Input text={text} setText={setText} /> <Preview text={text} /> </div> ); }const Input = ({ text, setText }) => { return ( <input value={text} onChange={(e) => setText(e.target.value)} /> ); }const Preview = ({ text }) => { return <p>{text}</p>; }Here,
i) State moved to Parent
ii) Parent becomes single source of truth
iii) Children become controlled componentsAdvantages of Lifting State Up
i) Single Source of Truth - No duplication → no inconsistency
ii) Better Synchronization - All components stay in sync automatically
iii) Easier Debugging - State lives in one place → easier to track
iv) Reusability - Child components become dumb/presentational
v) Predictable Data Flow - React follows one-way data flowconst Calculator = () => { const [temp, setTemp] = useState(""); return ( <> <CelsiusInput temp={temp} setTemp={setTemp} /> <FahrenheitInput temp={temp} setTemp={setTemp} /> </> ); }Lifting state vs Context API
Lifting State Up → pass via props
State is moved to the nearest common parent and passed down via props.
Context API → share globally without prop drilling
State is stored in a global-like container and accessed directly by any component./* Lifting the State up */ Parent ├── Child A (gets props) └── Child B (gets props) /* Context API - Direct Access */ Provider / | \ CompA CompB CompC (all access directly)When to Use Lifting State Up
i) Few components need the state - 2–3 related components
ii) Components are closely related - Siblings or parent-child
iii) Simple data flow - No deep nesting
When to Use Context API
i) Many components need the same state - Across different levels
ii) Deep component tree - Avoid prop drilling
iii) Global app data