Skip to main content

Command Palette

Search for a command to run...

19) Lifting state up

Updated
View as Markdown
  1. 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 state

  2. Example

    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 components

  3. Advantages 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 flow

    const Calculator = () => {
      const [temp, setTemp] = useState("");
    
      return (
        <>
          <CelsiusInput temp={temp} setTemp={setTemp} />
          <FahrenheitInput temp={temp} setTemp={setTemp} />
        </>
      );
    }
    
  4. 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