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

推荐订阅源

D
Docker
月光博客
月光博客
B
Blog RSS Feed
C
Check Point Blog
WordPress大学
WordPress大学
T
Tailwind CSS Blog
GbyAI
GbyAI
H
Help Net Security
Y
Y Combinator Blog
I
InfoQ
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
美团技术团队
博客园 - 三生石上(FineUI控件)
MongoDB | Blog
MongoDB | Blog
Jina AI
Jina AI
A
About on SuperTechFans
G
Google Developers Blog
爱范儿
爱范儿
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
U
Unit 42
人人都是产品经理
人人都是产品经理

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
React Hooks Explained: useReducer and useMemo for Beginners
Vinayagam · 2026-05-15 · via DEV Community

Introduction

When I started learning React, I mostly used useState for everything. It worked well in the beginning, but as my project became a little bigger, managing state became confusing. I had multiple values, and sometimes one value depended on another. That is when I started learning about useReducer and useMemo.

In this blog, I will explain both in a simple way based on my understanding as a beginner.

useReducer

useReducer is a React Hook used to manage state in a more structured way. Instead of directly updating state like in useState, we use a separate function called a reducer. This function decides how the state should change.

The basic syntax looks like this:

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

Enter fullscreen mode Exit fullscreen mode

Here, state stores the current value, and dispatch is used to send an action. The reducer function takes the current state and the action, and returns a new state.

A simple reducer function looks like this:

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      return state;
  }
}

Enter fullscreen mode Exit fullscreen mode

When I first saw this, it looked confusing, but later I understood that the action simply tells what needs to be done. For example, if I want to increase the count, I can write:

dispatch({ type: "increment" });

Enter fullscreen mode Exit fullscreen mode

This will call the reducer and update the state.

Using it inside a component looks like this:

const [state, dispatch] = useReducer(reducer, { count: 0 });

return (
  <div>
    <h2>{state.count}</h2>
    <button onClick={() => dispatch({ type: "increment" })}>+</button>
  </div>
);

Enter fullscreen mode Exit fullscreen mode

One thing I understood is that useReducer is very useful when state values are connected. For example, if I have count and total, and total depends on count, it is better to manage both together instead of using separate useState calls.

function reducer(state, action) {
  switch (action.type) {
    case "update":
      return {
        count: state.count + 1,
        total: state.total + state.count
      };
    default:
      return state;
  }
}

Enter fullscreen mode Exit fullscreen mode

This makes the logic easier to manage in one place.

useMemo

After learning useReducer, I faced another issue. My component was re-rendering again and again, and some calculations were running even when they were not needed. That is when I learned about useMemo.

useMemo is used to improve performance. It stores the result of a calculation and only recalculates it when required.

The syntax is simple:

const value = useMemo(() => {
  return calculation;
}, [dependencies]);

Enter fullscreen mode Exit fullscreen mode

At first, I did not understand what dependencies mean. Later I realized that dependencies are the values that control when the function should run again.

Here is a simple example:

const result = useMemo(() => {
  console.log("calculating");
  return count * 2;
}, [count]);

Enter fullscreen mode Exit fullscreen mode

In this example, the calculation runs only when count changes. If I update some other value like text input, this function will not run again.

const [count, setCount] = useState(0);
const [text, setText] = useState("");

const result = useMemo(() => count * 2, [count]);

return (
  <div>
    <h2>{result}</h2>
    <button onClick={() => setCount(count + 1)}>Increase</button>
    <input value={text} onChange={(e) => setText(e.target.value)} />
  </div>
);

Enter fullscreen mode Exit fullscreen mode

When I type in the input field, the component re-renders, but the calculation does not run again. This is how useMemo helps improve performance.