惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Stack Overflow Blog
Stack Overflow Blog
Forbes - Security
Forbes - Security
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
N
News | PayPal Newsroom
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Project Zero
Project Zero
Cyberwarzone
Cyberwarzone
Vercel News
Vercel News
M
MIT News - Artificial intelligence
云风的 BLOG
云风的 BLOG
Google Online Security Blog
Google Online Security Blog
Simon Willison's Weblog
Simon Willison's Weblog
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
T
Tenable Blog
I
InfoQ
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
D
DataBreaches.Net
博客园 - Franky
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
S
Security @ Cisco Blogs
Hacker News: Ask HN
Hacker News: Ask HN
J
Java Code Geeks
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Full Disclosure
C
Cisco Blogs
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Fortinet All Blogs
Jina AI
Jina AI
V
Visual Studio Blog
L
LINUX DO - 热门话题
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Advanced Hooks & State Management Patterns in React
Kushang Tail · 2026-05-29 · via DEV Community

Read Time: ~14 minutes | Building on React fundamentals to master state management at scale

Prerequisites: Familiarity with React basics, useState, useEffect (Part 1)


🔗 Series Navigation


📌 What You'll Learn

By the end of this guide, you'll understand:

  • ✅ Creating powerful custom hooks
  • ✅ When and how to use useReducer
  • ✅ Managing state globally with Context API
  • ✅ Redux fundamentals and when to use it
  • ✅ Modern alternatives: Zustand and Jotai
  • ✅ Choosing the right pattern for your project
  • ✅ Real-world shopping cart implementation

🎣 Custom Hooks: Reusing Logic Across Components

Custom hooks are regular JavaScript functions that let you extract component logic into reusable functions. They're one of the most powerful React patterns.

Rule #1: Custom Hooks Must Start with "use"

// ✅ Correct - starts with "use"
function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  return {
    value,
    bind: {
      value,
      onChange: e => setValue(e.target.value)
    },
    reset: () => setValue(initialValue)
  };
}

// ❌ Wrong - doesn't start with "use"
function formInput(initialValue) { ... }

Enter fullscreen mode Exit fullscreen mode

Example #1: useFormInput Hook

import { useState } from 'react';

function useFormInput(initialValue = '') {
  const [value, setValue] = useState(initialValue);

  return {
    value,
    setValue,
    bind: {
      value,
      onChange: e => setValue(e.target.value)
    },
    reset: () => setValue(initialValue)
  };
}

// Using the custom hook
function LoginForm() {
  const email = useFormInput('');
  const password = useFormInput('');

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(email.value, password.value);
    email.reset();
    password.reset();
  };

  return (
    <form onSubmit={handleSubmit}>
      <input {...email.bind} placeholder="Email" type="email" />
      <input {...password.bind} placeholder="Password" type="password" />
      <button type="submit">Login</button>
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

Why it's powerful: Logic is extracted once, reused everywhere. Need form input validation? Add it once to the hook.


Example #2: useFetch Hook - Data Loading Pattern

This is one of the most practical custom hooks for real projects:

import { useState, useEffect } from 'react';

function useFetch(url, options = {}) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true; // Prevent memory leaks

    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(url, options);
        if (!response.ok) throw new Error(`Error: ${response.status}`);

        const json = await response.json();
        if (isMounted) setData(json);
      } catch (err) {
        if (isMounted) setError(err.message);
      } finally {
        if (isMounted) setLoading(false);
      }
    };

    fetchData();
    return () => { isMounted = false; }; // Cleanup
  }, [url, options]);

  return { data, loading, error };
}

// Using it
function ProductList() {
  const { data: products, loading, error } = useFetch('/api/products');

  if (loading) return <p>Loading products...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {products.map(product => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

Enter fullscreen mode Exit fullscreen mode

Key insight: The component doesn't need to know about fetch logic—it just uses the hook.


Example #3: useLocalStorage Hook - Persistence Pattern

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  const setValue = (value) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(error);
    }
  };

  return [storedValue, setValue];
}

// Using it - Dark mode preference persists across page reloads
function App() {
  const [isDarkMode, setIsDarkMode] = useLocalStorage('darkMode', false);

  return (
    <div className={isDarkMode ? 'dark' : 'light'}>
      <button onClick={() => setIsDarkMode(!isDarkMode)}>
        Toggle Dark Mode
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode


🔄 useReducer: Complex State Logic

When you have multiple state variables that depend on each other, useReducer is cleaner than useState.

useReducer vs useState

Scenario Best Choice
Single simple value (count, toggle) useState
Multiple related values useReducer
State depends on previous state useReducer
Complex state transitions useReducer
Need to pass dispatch to children useReducer

Complete useReducer Example: Todo App

import { useReducer } from 'react';

// Reducer function - pure, testable
function todoReducer(state, action) {
  switch(action.type) {
    case 'ADD_TODO':
      return {
        ...state,
        todos: [...state.todos, {
          id: Date.now(),
          text: action.payload,
          completed: false
        }]
      };

    case 'TOGGLE_TODO':
      return {
        ...state,
        todos: state.todos.map(todo =>
          todo.id === action.payload
            ? { ...todo, completed: !todo.completed }
            : todo
        )
      };

    case 'DELETE_TODO':
      return {
        ...state,
        todos: state.todos.filter(todo => todo.id !== action.payload)
      };

    case 'SET_FILTER':
      return { ...state, filter: action.payload };

    default:
      return state;
  }
}

function TodoApp() {
  const initialState = {
    todos: [],
    filter: 'all' // all, active, completed
  };

  const [state, dispatch] = useReducer(todoReducer, initialState);

  const filteredTodos = state.todos.filter(todo => {
    if (state.filter === 'active') return !todo.completed;
    if (state.filter === 'completed') return todo.completed;
    return true;
  });

  return (
    <div>
      <input
        onKeyPress={(e) => {
          if (e.key === 'Enter') {
            dispatch({ type: 'ADD_TODO', payload: e.target.value });
            e.target.value = '';
          }
        }}
        placeholder="Add a todo..."
      />

      <ul>
        {filteredTodos.map(todo => (
          <li key={todo.id}>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => dispatch({ 
                type: 'TOGGLE_TODO', 
                payload: todo.id 
              })}
            />
            <span style={{
              textDecoration: todo.completed ? 'line-through' : 'none'
            }}>
              {todo.text}
            </span>
            <button onClick={() => dispatch({ 
              type: 'DELETE_TODO', 
              payload: todo.id 
            })}>
              Delete
            </button>
          </li>
        ))}
      </ul>

      <div>
        {['all', 'active', 'completed'].map(f => (
          <button
            key={f}
            onClick={() => dispatch({ type: 'SET_FILTER', payload: f })}
            style={{
              fontWeight: state.filter === f ? 'bold' : 'normal'
            }}
          >
            {f.charAt(0).toUpperCase() + f.slice(1)}
          </button>
        ))}
      </div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Why useReducer wins here:

  • All state changes go through dispatch—easy to debug and test
  • Reducer is a pure function—predictable and testable
  • Complex state logic stays organized in one place

🌍 Context API: Global State Without Libraries

Context API lets you share state across components without prop drilling.

Problem: Prop Drilling

// ❌ Passing props through 5 levels is messy
<App theme={theme} />
  <Header theme={theme} />
    <Nav theme={theme} />
      <Button theme={theme} />

Enter fullscreen mode Exit fullscreen mode

Solution: Context API

import { createContext, useContext, useState } from 'react';

// Step 1: Create context
const ThemeContext = createContext();

// Step 2: Create provider component
export function ThemeProvider({ children }) {
  const [isDark, setIsDark] = useState(false);

  const value = {
    isDark,
    toggleTheme: () => setIsDark(prev => !prev),
    colors: isDark
      ? { bg: '#1a1a1a', text: '#ffffff' }
      : { bg: '#ffffff', text: '#000000' }
  };

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}

// Step 3: Create custom hook to use context
export function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

// Step 4: Wrap your app
function App() {
  return (
    <ThemeProvider>
      <Header />
      <MainContent />
      <Footer />
    </ThemeProvider>
  );
}

// Step 5: Use anywhere
function Button() {
  const { isDark, toggleTheme, colors } = useTheme();

  return (
    <button
      onClick={toggleTheme}
      style={{ background: colors.bg, color: colors.text }}
    >
      {isDark ? '☀️ Light' : '🌙 Dark'}
    </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

When to use Context API:

  • ✅ Theme settings (light/dark mode)
  • ✅ User authentication state
  • ✅ Language/locale preferences
  • ❌ Frequently changing data (performance issues)

📦 Redux: Enterprise-Grade State Management

Redux is a predictable state container. It's overkill for small apps but essential for large ones.

Redux Flow

Action → Reducer → Store → Components Update

Enter fullscreen mode Exit fullscreen mode

Complete Redux Example: Shopping Cart

import { createStore } from 'redux';

// Step 1: Define initial state
const initialState = {
  items: [],
  total: 0,
  loading: false
};

// Step 2: Create reducer
function cartReducer(state = initialState, action) {
  switch(action.type) {
    case 'ADD_ITEM':
      const existingItem = state.items.find(
        item => item.id === action.payload.id
      );

      if (existingItem) {
        return {
          ...state,
          items: state.items.map(item =>
            item.id === action.payload.id
              ? { ...item, quantity: item.quantity + 1 }
              : item
          ),
          total: state.total + action.payload.price
        };
      }

      return {
        ...state,
        items: [...state.items, { ...action.payload, quantity: 1 }],
        total: state.total + action.payload.price
      };

    case 'REMOVE_ITEM':
      const removedItem = state.items.find(
        item => item.id === action.payload
      );
      return {
        ...state,
        items: state.items.filter(item => item.id !== action.payload),
        total: state.total - (removedItem.price * removedItem.quantity)
      };

    case 'CLEAR_CART':
      return initialState;

    default:
      return state;
  }
}

// Step 3: Create store
const store = createStore(cartReducer);

// Step 4: Dispatch actions
store.dispatch({
  type: 'ADD_ITEM',
  payload: { id: 1, name: 'Laptop', price: 1200 }
});

console.log(store.getState());
// { items: [{id: 1, name: 'Laptop', price: 1200, quantity: 1}], total: 1200 }

Enter fullscreen mode Exit fullscreen mode

Redux Pros & Cons:

  • ✅ Predictable state changes
  • ✅ Time-travel debugging (Redux DevTools)
  • ✅ Great for large, complex apps
  • ❌ Boilerplate code (actions, reducers, selectors)
  • ❌ Steep learning curve

⚡ Zustand: Lightweight Alternative to Redux

Zustand is simpler than Redux with minimal boilerplate.

import { create } from 'zustand';

// Create store in one place
const useCartStore = create((set) => ({
  items: [],
  total: 0,

  // Actions
  addItem: (item) => set((state) => ({
    items: [...state.items, item],
    total: state.total + item.price
  })),

  removeItem: (id) => set((state) => {
    const removedItem = state.items.find(item => item.id === id);
    return {
      items: state.items.filter(item => item.id !== id),
      total: state.total - removedItem.price
    };
  }),

  clearCart: () => set({
    items: [],
    total: 0
  })
}));

// Use anywhere - no Provider needed!
function ShoppingCart() {
  const { items, total, removeItem } = useCartStore();

  return (
    <div>
      <h2>Cart: ${total}</h2>
      {items.map(item => (
        <div key={item.id}>
          {item.name} - ${item.price}
          <button onClick={() => removeItem(item.id)}>Remove</button>
        </div>
      ))}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Why Zustand is Awesome:

  • ✅ No Provider wrapper needed
  • ✅ Minimal boilerplate
  • ✅ Great performance
  • ✅ TypeScript friendly
  • ✅ Smaller bundle size

🎯 Jotai: Atom-Based State Management

Jotai takes a different approach—primitive atoms instead of a single store.

import { atom, useAtom } from 'jotai';

// Create atoms (primitive pieces of state)
const cartItemsAtom = atom([]);
const cartTotalAtom = atom(0);

// Derived atom (computed from other atoms)
const cartCountAtom = atom(
  (get) => get(cartItemsAtom).length
);

// Use atoms in components
function ShoppingCart() {
  const [items, setItems] = useAtom(cartItemsAtom);
  const [total, setTotal] = useAtom(cartTotalAtom);
  const [count] = useAtom(cartCountAtom);

  const addItem = (item) => {
    setItems([...items, item]);
    setTotal(total + item.price);
  };

  return (
    <div>
      <h2>Cart ({count} items): ${total}</h2>
      <button onClick={() => addItem({ name: 'Laptop', price: 1200 })}>
        Add Laptop
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Jotai Benefits:

  • ✅ Fine-grained reactivity
  • ✅ Only components using changed atoms re-render
  • ✅ Great for complex interdependent state
  • ✅ No Provider overhead

🛒 Real-World Example: Shopping Cart with Multiple Patterns

Let's build a shopping cart using Context API + useReducer (the practical combination):

import { createContext, useContext, useReducer } from 'react';

// 1. Create context
const CartContext = createContext();

// 2. Reducer
function cartReducer(state, action) {
  switch(action.type) {
    case 'ADD_TO_CART': {
      const existingItem = state.items.find(
        item => item.id === action.payload.id
      );

      if (existingItem) {
        return {
          ...state,
          items: state.items.map(item =>
            item.id === action.payload.id
              ? { ...item, quantity: item.quantity + 1 }
              : item
          )
        };
      }

      return {
        ...state,
        items: [...state.items, { ...action.payload, quantity: 1 }]
      };
    }

    case 'REMOVE_FROM_CART':
      return {
        ...state,
        items: state.items.filter(item => item.id !== action.payload)
      };

    case 'UPDATE_QUANTITY':
      return {
        ...state,
        items: state.items.map(item =>
          item.id === action.payload.id
            ? { ...item, quantity: action.payload.quantity }
            : item
        ).filter(item => item.quantity > 0)
      };

    case 'CLEAR_CART':
      return { ...state, items: [] };

    default:
      return state;
  }
}

// 3. Provider component
export function CartProvider({ children }) {
  const [state, dispatch] = useReducer(cartReducer, { items: [] });

  const total = state.items.reduce(
    (sum, item) => sum + (item.price * item.quantity),
    0
  );

  const value = {
    items: state.items,
    total,
    addToCart: (product) => dispatch({ type: 'ADD_TO_CART', payload: product }),
    removeFromCart: (id) => dispatch({ type: 'REMOVE_FROM_CART', payload: id }),
    updateQuantity: (id, quantity) => dispatch({
      type: 'UPDATE_QUANTITY',
      payload: { id, quantity }
    }),
    clearCart: () => dispatch({ type: 'CLEAR_CART' })
  };

  return (
    <CartContext.Provider value={value}>
      {children}
    </CartContext.Provider>
  );
}

// 4. Custom hook
export function useCart() {
  const context = useContext(CartContext);
  if (!context) {
    throw new Error('useCart must be used within CartProvider');
  }
  return context;
}

// 5. Usage
function ProductCard({ product }) {
  const { addToCart } = useCart();

  return (
    <div>
      <h3>{product.name}</h3>
      <p>${product.price}</p>
      <button onClick={() => addToCart(product)}>
        Add to Cart
      </button>
    </div>
  );
}

function Cart() {
  const { items, total, removeFromCart, updateQuantity } = useCart();

  return (
    <div>
      <h2>Shopping Cart</h2>
      {items.length === 0 ? (
        <p>Your cart is empty</p>
      ) : (
        <>
          {items.map(item => (
            <div key={item.id}>
              <h4>{item.name}</h4>
              <input
                type="number"
                value={item.quantity}
                onChange={(e) => updateQuantity(item.id, parseInt(e.target.value))}
              />
              <p>${item.price * item.quantity}</p>
              <button onClick={() => removeFromCart(item.id)}>Remove</button>
            </div>
          ))}
          <h3>Total: ${total.toFixed(2)}</h3>
        </>
      )}
    </div>
  );
}

// 6. App structure
function App() {
  return (
    <CartProvider>
      <ProductCard product={{ id: 1, name: 'Laptop', price: 1200 }} />
      <Cart />
    </CartProvider>
  );
}

Enter fullscreen mode Exit fullscreen mode


🎯 Choosing Your State Management Tool

Decision Tree

Is your app small (< 5 components)?
├─ Yes → Use useState directly
└─ No → Continue

Do you need to share state between many components?
├─ Yes → Continue
└─ No → Use useState + prop drilling

Is the state changing frequently (> 10 times/sec)?
├─ Yes → Use Jotai or Zustand
└─ No → Continue

Is your team familiar with Redux?
├─ Yes → Consider Redux
└─ No → Consider Zustand

Do you need middleware (logging, analytics)?
├─ Yes → Use Redux
└─ No → Use Zustand or Context API

Enter fullscreen mode Exit fullscreen mode

Quick Comparison

Tool Best For Learning Curve Bundle Size
useState Simple state Easiest 0 KB
useReducer Complex state Easy 0 KB
Context API Theme, auth Easy 0 KB
Redux Large apps Hard 10 KB
Zustand Medium apps Easy 2 KB
Jotai Granular updates Medium 5 KB

🎓 Performance Considerations

Context API Performance Pitfall

// ❌ BAD - Entire app re-renders on state change
function ThemeProvider({ children }) {
  const [isDark, setIsDark] = useState(false);

  return (
    <ThemeContext.Provider value={{ isDark, setIsDark }}>
      {children}
    </ThemeContext.Provider>
  );
}

// ✅ GOOD - Memoize context value
function ThemeProvider({ children }) {
  const [isDark, setIsDark] = useState(false);

  const value = useMemo(() => ({ isDark, setIsDark }), [isDark]);

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}

Enter fullscreen mode Exit fullscreen mode

Key insight: Zustand and Jotai automatically optimize this. Redux requires careful selector use.


🚀 Advanced Pattern: Combining Approaches

Real projects often use multiple state management tools:

// Global app state → Redux/Zustand
// Theme & Auth → Context API
// UI state (modals, dropdowns) → useState
// Form data → Custom useForm hook

Enter fullscreen mode Exit fullscreen mode

This is normal and healthy—don't over-engineer.


💡 Final Thoughts: State Management Maturity

Beginner Phase

  • Use useState everywhere
  • Props for simple sharing
  • useReducer when state gets complex

Intermediate Phase

  • Context API for theme, auth, user
  • useReducer for complex components
  • Custom hooks for reusable logic

Advanced Phase

  • Zustand for app state
  • Context for cross-cutting concerns
  • Jotai for highly granular updates
  • Redux only if you have 50+ components

📚 Key Takeaways

  1. Custom hooks are the foundation—master these first
  2. useReducer scales better than useState for complex state
  3. Context API is perfect for theme/auth, not data caches
  4. Zustand is the modern, simple alternative to Redux
  5. Jotai excels at fine-grained reactivity
  6. Choose based on app size, not hype

🔗 Quick Resources


💬 What's Your State Management Journey?

Have you struggled with prop drilling? Built a custom hook? Migrated from Redux? Share your experience in the comments—I'd love to hear what state management patterns your team uses!


📖 Series Roadmap

Next in Part 3:

  • useMemo & useCallback deep dive
  • Code splitting and lazy loading
  • Suspense and React.lazy()
  • Performance profiling with DevTools
  • Real optimization case studies

Happy state managing! 🚀