State Management

Subject: React

πŸ” What is State Management?

In React, state refers to data that drives component behavior and UI rendering.

State Management is the technique of controlling how that data is created, updated, and shared across components.


πŸͺœ 2. Lifting State Up

βœ… What It Means

When multiple sibling components need access to shared state, move the state to their nearest common parent.

πŸ“¦ Example


πŸͺ’ 3. Prop Drilling

πŸ” What It Means

Prop Drilling is when you pass data through multiple components β€” even if some intermediate ones don’t use it.

πŸ” Example

Problem: Parent has to pass down user even if it doesn't need it.


🌐 4. Context API

βœ… Why Use It?

To avoid prop drilling and make shared state accessible deep in the component tree.

πŸ› οΈ Step-by-Step

1. Create Context

2. Provide Context

3. Consume Context


🧰 5. External State Management Libraries

When your app grows, Context may become hard to manage or inefficient. That's where state libraries come in.

πŸ” Redux

βœ… Core Features

  • Centralized global store
  • Actions & reducers for logic
  • Middleware support (e.g., Redux Thunk)

πŸ§ͺ Example Flow

1. Create Slice

2. Configure Store

3. Wrap in Provider

4. Use in Component


⚑ Zustand

βœ… Features

  • Minimal API (just one hook)
  • No boilerplate
  • Fast and simple

🧬 Recoil

βœ… Features

  • Built for React
  • State via atoms
  • Supports async selectors

🧠 When to Use What?

Use CaseTool/Pattern
Small local stateuseState
Shared state between siblingsLifting State Up
Avoid prop drillingContext API
Large-scale global stateRedux / Zustand
Async derived state & reactivityRecoil

βœ… Summary

ToolBest ForTypeComplexity
useStateLocal UI stateBuilt-inLow
Lifting StateSharing state among siblingsBuilt-inLow
Context APIAvoiding prop drillingBuilt-inMedium
ReduxLarge apps with global state needsExternalHigh
ZustandSimple global state with hooksExternalLow
RecoilAtom-based reactivity + async dataExternalMedium