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

推荐订阅源

T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
L
LINUX DO - 热门话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
博客园_首页
MongoDB | Blog
MongoDB | Blog
V
V2EX
GbyAI
GbyAI
量子位
Microsoft Azure Blog
Microsoft Azure Blog
有赞技术团队
有赞技术团队
G
Google Developers Blog
云风的 BLOG
云风的 BLOG
B
Blog
Microsoft Security Blog
Microsoft Security Blog
S
SegmentFault 最新的问题
O
OpenAI News
N
News and Events Feed by Topic
博客园 - Franky
爱范儿
爱范儿
Forbes - Security
Forbes - Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V2EX - 技术
V2EX - 技术
Application and Cybersecurity Blog
Application and Cybersecurity Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Schneier on Security
Schneier on Security
Cloudbric
Cloudbric
Security Archives - TechRepublic
Security Archives - TechRepublic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recent Commits to openclaw:main
Recent Commits to openclaw:main
人人都是产品经理
人人都是产品经理
P
Privacy International News Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
D
DataBreaches.Net
Last Week in AI
Last Week in AI
罗磊的独立博客
Spread Privacy
Spread Privacy
Recent Announcements
Recent Announcements
The Cloudflare Blog
Google DeepMind News
Google DeepMind News
AWS News Blog
AWS News Blog
The Register - Security
The Register - Security
Y
Y Combinator Blog
J
Java Code Geeks
I
Intezer

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
Learn React useMemo the Right Way — Re-Renders, Optimization,Dependencies & useEffect
Kathirvel S · 2026-05-14 · via DEV Community

Welcome back to “Let’s Master React Hooks Together” — the series where we learn React hooks step by step in the most beginner-friendly way possible.

So far in this series, we’ve already explored hooks like useState and useEffect, and by now you’ve probably started noticing one important thing about React:

React components re-render a lot.

And honestly, that’s completely normal. React is designed that way.

But once applications start growing, re-rendering can sometimes create performance problems — especially when expensive calculations run again and again unnecessarily.

That’s exactly where today’s hook enters the picture:

useMemo()

Enter fullscreen mode Exit fullscreen mode

At first glance, useMemo looks confusing. Many beginners memorize the syntax without actually understanding:

  • what problem it solves,
  • why it exists,
  • and how it connects with useEffect.

So in this 8th episode, we’re going to slow things down and understand useMemo properly from the ground up.

We’ll learn:

  • the official definition,
  • beginner-friendly explanation,
  • how memoization works,
  • how dependency arrays behave,
  • how useEffect connects with useMemo,
  • why useEffect does not return values,
  • and how useMemo actually returns optimized values.

And just like the previous episodes in this series, we’ll not only write code — we’ll also break down the execution flow step by step so you can understand what React is actually doing behind the scenes.

So let’s dive in and finally make useMemo feel simple.


Official Definition of useMemo

According to the React documentation:

useMemo is a React Hook that lets you cache the result of a calculation between re-renders.

This is the official explanation. But honestly, for beginners, this sentence alone is not very easy to understand.

So let’s simplify it.


Beginner Friendly Definition of useMemo

In simple words:

useMemo remembers a calculated value so React doesn’t calculate it again and again during every re-render.

Or even simpler:

useMemo helps React avoid unnecessary work.

That is the core idea.

React components re-render frequently. During those renders, calculations also run again. If some calculation is expensive, repeatedly running it can slow down the application. useMemo helps optimize that.


Before Learning useMemo, Understand Re-Rendering

To properly understand useMemo, you first need to understand one very important concept in React:

React re-renders components very often.

Whenever:

  • state changes,
  • props change,
  • or parent components re-render,

React runs the component function again.

Look at this example:

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  console.log("Component Rendered");

  return (
    <div>
      <h1>{count}</h1>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

At first, this code looks very small and harmless. But internally, React is doing more than beginners realize.


Step-by-Step Flow of the Code

When the component loads for the first time, React starts executing:

function App()

Enter fullscreen mode Exit fullscreen mode

Inside the component, React creates state using:

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

Enter fullscreen mode Exit fullscreen mode

Now:

  • count becomes 0
  • setCount becomes the function that updates state

After that, this line runs:

console.log("Component Rendered");

Enter fullscreen mode Exit fullscreen mode

Then React returns the JSX and displays the UI.

When the button is clicked:

setCount(count + 1)

Enter fullscreen mode Exit fullscreen mode

React updates the state.

And this is the important part:

React re-renders the entire component again.

That means:

  • the component function runs again,
  • variables recreate,
  • functions recreate,
  • calculations rerun,
  • console logs rerun.

This behavior is exactly why hooks like useMemo exist.


Why useMemo Exists

Most of the time, re-rendering is completely fine. React is fast.

But imagine your component contains:

  • huge filtering logic,
  • expensive calculations,
  • sorting large arrays,
  • heavy data processing.

Now every re-render becomes expensive.

Even unrelated state changes can trigger those calculations again.

That creates unnecessary work.

To solve this optimization problem, React introduced:

useMemo()

Enter fullscreen mode Exit fullscreen mode

Its job is simple:

  • remember old calculated results,
  • and reuse them if dependencies did not change.

Official Syntax of useMemo

const memoizedValue = useMemo(() => {
  return expensiveCalculation();
}, [dependencies]);

Enter fullscreen mode Exit fullscreen mode

At first glance, this syntax may look scary. But it becomes simple once we break it down carefully.


Understanding the Syntax Step by Step

The first part is the function:

() => {
  return expensiveCalculation();
}

Enter fullscreen mode Exit fullscreen mode

This contains the calculation React should remember.

And notice something important here:

return expensiveCalculation();

Enter fullscreen mode Exit fullscreen mode

useMemo RETURNS a value.

This is one of the biggest differences between useMemo and useEffect.

Then comes the dependency array:

[dependencies]

Enter fullscreen mode Exit fullscreen mode

This tells React:

“Only rerun this calculation if these values change.”

This dependency system is exactly why beginners often connect useMemo with useEffect.

Because useEffect also uses dependency arrays.


Official Definition of useEffect

According to React:

useEffect lets you synchronize a component with external systems.

That sounds complicated too.

So let’s simplify it.


Beginner Friendly Definition of useEffect

In simple words:

useEffect runs some code after rendering.

Usually developers use it for:

  • API calls,
  • timers,
  • localStorage,
  • subscriptions,
  • DOM updates.

So while useMemo focuses on remembering values, useEffect focuses on running actions.


Very Important Difference

useEffect Does NOT Return Values

This is one of the most important beginner understandings.

Look at this:

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

Enter fullscreen mode Exit fullscreen mode

Here:

useMemo

Enter fullscreen mode Exit fullscreen mode

returns a value.

That returned value gets stored inside:

value

Enter fullscreen mode Exit fullscreen mode

Now compare it with:

useEffect(() => {
  console.log("Hello");
}, []);

Enter fullscreen mode Exit fullscreen mode

This does NOT return a UI value.

useEffect simply runs some code after rendering.

So:

Hook Returns Value?
useMemo Yes
useEffect No

This is a very important connectivity proof between both hooks.

One stores values.
The other performs actions.


Important Connection Between useMemo and useEffect

This is where many beginners get confused.

Both hooks use dependency arrays.

Example:

useEffect(() => {
  console.log("Effect running");
}, [count]);

Enter fullscreen mode Exit fullscreen mode

and

useMemo(() => {
  return count * 2;
}, [count]);

Enter fullscreen mode Exit fullscreen mode

Both are watching:

[count]

Enter fullscreen mode Exit fullscreen mode

Whenever count changes:

  • useEffect reruns,
  • useMemo recalculates.

That’s why they feel similar.

But internally, their purpose is different.


Difference Between useMemo and useEffect

The easiest way to understand them is this:

Hook Purpose
useMemo Remember calculated values
useEffect Run side effects/actions

You can also remember it like this:

useMemo

“Remember this value.”

useEffect

“Run this action.”

This one-line understanding helps a lot.


Example Without useMemo

Now let’s see the real problem.

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  const [dark, setDark] = useState(false);

  function slowFunction(num) {
    console.log("Heavy Calculation Running...");

    for (let i = 0; i < 1000000000; i++) {}

    return num * 2;
  }

  const doubledNumber = slowFunction(count);

  return (
    <div>
      <h1>{doubledNumber}</h1>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>

      <button onClick={() => setDark(!dark)}>
        Toggle Theme
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

At first, this code may look fine. But there’s an important issue hidden inside it.


What Happens Internally Here?

When the component renders:

  • slowFunction(count) runs,
  • heavy calculation happens,
  • React displays the result.

Now suppose the user clicks:

Toggle Theme

Enter fullscreen mode Exit fullscreen mode

This updates:

dark

Enter fullscreen mode Exit fullscreen mode

state.

Even though:

  • count did not change,
  • the heavy calculation still runs again.

Why?

Because React re-rendered the component, and everything inside the component executed again.

That is unnecessary work.

This is exactly where useMemo helps.


Fixing It with useMemo

import { useMemo, useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  const [dark, setDark] = useState(false);

  function slowFunction(num) {
    console.log("Heavy Calculation Running...");

    for (let i = 0; i < 1000000000; i++) {}

    return num * 2;
  }

  const doubledNumber = useMemo(() => {
    return slowFunction(count);
  }, [count]);

  return (
    <div>
      <h1>{doubledNumber}</h1>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>

      <button onClick={() => setDark(!dark)}>
        Toggle Theme
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Now the behavior changes.


Flow of This Code

When the component renders for the first time:

  • useMemo runs,
  • slowFunction(count) executes,
  • React stores the result,
  • React also stores the dependency:
[count]

Enter fullscreen mode Exit fullscreen mode

Now suppose theme changes.

React re-renders the component again.

But before recalculating, React compares old dependencies with new dependencies.

If:

count

Enter fullscreen mode Exit fullscreen mode

did not change,
React skips the expensive calculation and reuses the old stored value.

This is called:

memoization

Enter fullscreen mode Exit fullscreen mode

And that’s where the name useMemo comes from.


Combining useMemo with useEffect

Now let’s connect both hooks together.

import { useEffect, useMemo, useState } from "react";

function App() {
  const [number, setNumber] = useState(1);

  const squared = useMemo(() => {
    console.log("Calculating...");
    return number * number;
  }, [number]);

  useEffect(() => {
    console.log("Squared value changed:", squared);
  }, [squared]);

  return (
    <div>
      <h1>{squared}</h1>

      <button onClick={() => setNumber(number + 1)}>
        Increase
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

This example is the best proof of connectivity between:

  • useMemo
  • and useEffect

Now get in to this flow

When the component loads:

  • number state initializes,
  • useMemo calculates:
number * number

Enter fullscreen mode Exit fullscreen mode

  • React stores the returned value inside:
squared

Enter fullscreen mode Exit fullscreen mode

This proves:

useMemo

Enter fullscreen mode Exit fullscreen mode

returns a value.

Now React renders the UI.

After rendering finishes:

useEffect

Enter fullscreen mode Exit fullscreen mode

runs.

Notice:

  • useEffect did not create a value,
  • it only performed an action:
console.log()

Enter fullscreen mode Exit fullscreen mode

This proves:

useEffect

Enter fullscreen mode Exit fullscreen mode

does NOT return UI values.

Now suppose the button is clicked.

setNumber(number + 1)

Enter fullscreen mode Exit fullscreen mode

updates state.

React re-renders again.

Then:

  • useMemo checks [number]
  • dependency changed,
  • calculation reruns,
  • new squared value gets returned.

Now:

useEffect

Enter fullscreen mode Exit fullscreen mode

detects that:

[squared]

Enter fullscreen mode Exit fullscreen mode

changed.

So the effect runs again.

This is the real relationship:

  • useMemo creates optimized returned values
  • useEffect reacts when those values change

Once beginners understand this execution flow, both hooks become much easier.


Common Beginner Mistakes

One of the biggest beginner mistakes is using useMemo everywhere.

Example:

const value = useMemo(() => {
  return count + 1;
}, [count]);

Enter fullscreen mode Exit fullscreen mode

This is unnecessary because:

count + 1

Enter fullscreen mode Exit fullscreen mode

is already extremely fast.

useMemo itself also has a small cost.

So optimization should only happen when calculations are actually expensive.

Another common mistake is incorrect dependencies:

useMemo(() => {
  return count * 2;
}, []);

Enter fullscreen mode Exit fullscreen mode

Now the value never updates because dependencies are empty.

The same dependency problems also happen in useEffect.

So dependency arrays are very important in both hooks.


Final Thoughts

For beginners, useMemo feels confusing because it introduces optimization concepts early.

But the core idea is actually simple.

React components re-render often. During those renders, calculations also rerun. If those calculations are expensive, useMemo helps React remember previous results and avoid unnecessary work.

At the same time:

  • useMemo returns optimized values,
  • while useEffect performs actions after rendering.

So together:

  • useMemo stores optimized calculated values,
  • useEffect reacts when values change.

And that’s a wrap for Episode 8 of “Let’s Master React Hooks Together.”

If useMemo felt confusing before, hopefully now it feels much more practical and less scary.

In the next episodes, we’ll continue exploring more React hooks, deeper concepts, and real-world React patterns step by step in the same beginner-friendly style.

Until then:

  • experiment with these examples,
  • change dependencies,
  • observe re-renders,
  • and keep building projects.

Because the more you practice React hooks, the more natural they become.

See you in Episode 9 of “Let’s Master React Hooks Together.”