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

推荐订阅源

A
About on SuperTechFans
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Tenable Blog
WordPress大学
WordPress大学
小众软件
小众软件
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 聂微东
大猫的无限游戏
大猫的无限游戏
T
The Exploit Database - CXSecurity.com
Attack and Defense Labs
Attack and Defense Labs
Simon Willison's Weblog
Simon Willison's Weblog
C
CXSECURITY Database RSS Feed - CXSecurity.com
量子位
有赞技术团队
有赞技术团队
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
F
Fortinet All Blogs
S
Schneier on Security
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
Martin Fowler
Martin Fowler
Recent Announcements
Recent Announcements
Stack Overflow Blog
Stack Overflow Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
阮一峰的网络日志
阮一峰的网络日志
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
F
Full Disclosure
Scott Helme
Scott Helme
GbyAI
GbyAI
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
Cloudbric
Cloudbric
云风的 BLOG
云风的 BLOG
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
Hacker News - Newest:
Hacker News - Newest: "LLM"
Security Latest
Security Latest
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
MongoDB | Blog
MongoDB | Blog
The GitHub Blog
The GitHub Blog
The Register - Security
The Register - Security
L
Lohrmann on Cybersecurity
PCI Perspectives
PCI Perspectives
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
D
Docker
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Secure Thoughts
C
Check Point Blog

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
How React Works (Part 4)? The Idea That Makes Suspense Possible
Sam Abaasi · 2026-05-02 · via DEV Community

The Idea That Makes Suspense Possible

Series: How React Works Under the Hood
Part 1: Motivation Behind React Fiber: Time Slicing & Suspense
Part 2: Why React Had to Build Its Own Execution Engine
Part 3: How React Finds What Actually Changed
Prerequisites: Read Parts 1–3 first.


A Question Before We Start

Think about how you fetch data in a React component today. You probably do something like this:

function UserProfile({ id }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchUser(id).then(data => {
      setUser(data);
      setLoading(false);
    });
  }, [id]);

  if (loading) return <Spinner />;
  return <div>{user.name}</div>;
}

Enter fullscreen mode Exit fullscreen mode

It works. But look at what you had to do: manage two pieces of state, write an effect, handle the loading condition manually, repeat this pattern in every component that fetches data.

Now look at what Suspense lets you write instead:

function UserProfile({ id }) {
  const user = fetchUser(id); // just... read the data
  return <div>{user.name}</div>;
}

<Suspense fallback={<Spinner />}>
  <UserProfile id={1} />
</Suspense>

Enter fullscreen mode Exit fullscreen mode

No loading state. No effect. No condition. The component just reads data as if it's already there. If it isn't, React handles the waiting — including showing the spinner — automatically.

How is this possible? How can a component just "pause" mid-render and resume when data arrives?

The answer involves a concept called algebraic effects — and understanding it will make Suspense, ErrorBoundary, and some of React's most surprising behaviors finally make sense.


Start With Something You Already Know: throw

Algebraic effects sound academic. But Dan Abramov wrote one of the best explanations of them, and he started with something every JavaScript developer already knows: try / catch.

Here's how throw works:

function getName(user) {
  if (user.name === null) {
    throw new Error('no name');
  }
  return user.name;
}

try {
  getName(user);
} catch (err) {
  console.log('handled:', err.message);
}

Enter fullscreen mode Exit fullscreen mode

Notice what throw actually does. It doesn't decide what happens when the error occurs. It just signals that something happened. The catch block somewhere up the call stack is what decides the behavior.

This separation — signaling something vs handling it — is the core idea.

And notice: it doesn't matter how deep getName is in the call stack. It could be called 100 functions deep. throw bypasses all of them and finds the nearest catch. The middle layers don't have to do anything. They don't even know about the error.


The Problem With try / catch: No Coming Back

try / catch has one limitation that matters a lot.

When you throw, execution stops at that point. The catch block runs. And that's it — you can never go back to the line that threw and continue from there.

function getName(user) {
  if (user.name === null) {
    throw new Error('no name');
    // ← once you throw, you can NEVER resume here
  }
  return user.name;
}

Enter fullscreen mode Exit fullscreen mode

For errors, this makes sense. But what if you wanted to ask the surrounding context a question and then continue based on the answer?

Like: "I need this user's name. I don't have it. Can someone provide it? I'll wait here."

That's what algebraic effects enable. Dan Abramov described it as a "resumable try / catch."


Algebraic Effects: A Resumable try / catch

Algebraic effects don't exist in JavaScript yet. They're a research concept — supported only by a handful of languages built specifically to explore the idea. But Dan Abramov explained them using a hypothetical JavaScript dialect, and his explanation is the clearest one I've found. Let's walk through it.

Imagine JavaScript had two new keywords: perform and resume with.

perform works like throw — it signals something to the surrounding context and finds the nearest handler up the call stack. The crucial difference: it doesn't stop execution. The handler can call resume with to jump back to exactly where perform was called and continue from there, passing a value back in.

Here's Dan's example. We have a function that needs a user's name but doesn't have it:

// Hypothetical JavaScript — this doesn't exist yet
function getName(user) {
  if (user.name === null) {
    // 1. Signal: "I need a name" — but don't stop
    const name = perform 'ask_name';
    // 4. Resume here — name is now 'Arya Stark'
  }
  return user.name;
}

try {
  makeFriends(arya, gendry);
} handle (effect) {
  if (effect === 'ask_name') {
    // 2. Handler catches it — like catch
    // 3. Resume with a value — unlike catch
    resume with 'Arya Stark';
  }
}

Enter fullscreen mode Exit fullscreen mode

The numbered steps show what happens: perform signals (1), the handler catches it (2), the handler provides a value (3), execution jumps back to where perform was and continues with that value (4).

Notice what this doesn't require. makeFriends — the function between getName and the handler — doesn't know anything about this. It didn't have to be modified. It didn't have to pass anything through. The effect just bypassed it entirely, exactly like throw bypasses intermediate functions on its way to catch.

This is what Dan calls "a function has no color." With async/await, making one function async infects every function above it — they all have to become async too. With algebraic effects, a deeply nested function can perform an effect without any of the layers above it caring. The handler somewhere at the top decides what to do, and execution resumes as if nothing unusual happened.

What makes this more powerful than try / catch

With regular try / catch, the handler is always synchronous and can never return a value back to the thrower. With algebraic effects, the handler can:

  • Respond synchronously — resume with an immediate value
  • Respond asynchronously — call resume with inside a setTimeout or after a fetch
  • The code that did perform doesn't need to know which one happened

This last point is the key. The same getName function works whether the handler looks up the name from memory, fetches it from a database, or generates it randomly. The function that needs the effect is completely decoupled from how the effect is fulfilled.

bypasses middle layers → handler → resume with value → continues at perform point

That decoupling — signal here, handle somewhere above, resume back here — is the entire concept. And it maps almost exactly onto what React does with Suspense.


Suspense Is React's Implementation of This Idea

JavaScript doesn't actually have perform and resume with. They don't exist. But React simulates this pattern using the tools JavaScript does have: throw and Fiber.

Here's what actually happens when a component suspends:

The component throws a Promise.

When fetchUser(id) is called and the data isn't in the cache yet, instead of returning null or undefined, it throws a Promise — the Promise that will resolve when the data arrives.

// Inside the data fetching library
function fetchUser(id) {
  const cached = cache.get(id);

  if (cached === 'pending') {
    throw promise; // ← this is the "perform"
  }
  if (cached === 'resolved') {
    return cache.get(id); // ← data is ready, return normally
  }

  // Start the fetch, mark as pending, throw
  const promise = fetch(`/users/${id}`).then(data => cache.set(id, data));
  cache.set(id, 'pending');
  throw promise;
}

Enter fullscreen mode Exit fullscreen mode

React catches the thrown Promise.

Because React's render loop runs inside a try / catch, it catches the thrown Promise. This is the "handler" in the algebraic effects model — React itself acts as the effect handler.

React shows the fallback.

React walks up the Fiber tree to find the nearest <Suspense> boundary and shows its fallback — the <Spinner /> — while waiting.

When the Promise resolves, React retries.

When the data arrives, React re-renders the component from the <Suspense> boundary downward. This time, the cache has the data. fetchUser returns normally instead of throwing. The component renders successfully.

As Sam Galson described it:

"A component is able to suspend the fiber it is running in by throwing a promise, which is caught and handled by the framework. When the promise resolves, its value is added to a cache, the fiber is restarted, and the next time the data is requested it is accessed synchronously from cache."

component throws Promise → Suspense boundary catches → shows fallback → Promise resolves → retry → renders


Why This Only Works Because of Fiber

Here's the critical question: when a component throws mid-render, wouldn't all the work React did to reach that point be lost?

With the old synchronous call stack — yes. Throwing would unwind the entire stack, destroying every local variable and stack frame on the way up.

But React uses Fiber, not the native call stack, to track rendering work. Fibers are plain JavaScript objects — they survive the throw. They sit in memory exactly as they were.

When React catches the thrown Promise and shows the fallback, all the Fiber work up to that point is preserved. When the data arrives and React retries, it resumes from the Suspense boundary without re-doing all the ancestor work.

This is what Sam Galson meant when he wrote that the throw-based approach "isn't problematic for React because it relies on fibers not the native call stack to track program execution."

Fiber made algebraic-effect-style control flow possible in JavaScript. Without Fiber, throwing a Promise would be catastrophic. With Fiber, it's just a pause.


ErrorBoundary Is the Same Pattern

Once you understand Suspense through this lens, ErrorBoundary becomes obvious — it's the same mechanism, just for actual errors instead of Promises.

When a component throws an error during rendering, React walks up the Fiber tree looking for the nearest class component that implements getDerivedStateFromError. When it finds one, it re-renders that component with error state, showing the fallback UI instead of the crashed subtree.

The component that threw didn't decide what happens — it just threw. The ErrorBoundary somewhere up the tree decided the behavior. Sound familiar?

That's the same separation as perform and handle. The throwing component signals something happened. The handler decides what to do.

class ErrorBoundary extends React.Component {
  static getDerivedStateFromError(error) {
    return { hasError: true }; // ← this is the "handle"
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

Enter fullscreen mode Exit fullscreen mode

The key difference from Suspense: ErrorBoundary doesn't resume. Once a component threw an error, that render is abandoned. The boundary re-renders with fallback. Suspense, by contrast, genuinely retries the original render when the data arrives.

ErrorBoundary vs Suspense — both catch throws, ErrorBoundary shows fallback permanently, Suspense retries


The Bigger Picture

Dan Abramov wrote in his algebraic effects article that the React team — specifically Sebastian Markbåge — had been using algebraic effects as a mental model for years:

"My colleague Sebastian kept referring to them as a mental model for some things we do inside of React. At some point, it became a running joke on the React team."

Hooks follow the same idea too. When you call useState inside a component, that component doesn't know or care where its state is actually stored. It just performs a "request for state" and React — the handler — provides it from the Fiber's hook linked list. The component doesn't reach into React's internals. React provides the value through the call.

This separation — components declaring what they need, React deciding how to provide it — is algebraic effects thinking applied to a UI library. And it's why React's API feels declarative even when the underlying behavior is complex.


What's Coming in Part 5

In Part 5 we look at the React lifecycle from the inside — initial mount, re-render, useEffect, and useLayoutEffect. We'll trace exactly when each fires, why the order is what it is, and what "after the browser paints" actually means.


🎬 Watch These

Sam Galson — Magic in the web of it: coroutines, continuations, fibers | React Advanced London
The CS foundation — fibers, coroutines, and how React uses the throw/catch mechanism to simulate algebraic effects. The source for the Fiber + algebraic effects connection in this article.

Matheus Albuquerque — Inside Fiber | React Summit 2022
Start at 12:46 — Matheus shows how Context API was designed using algebraic effects thinking, and how Suspense connects to it.


🙏 Sources & Thanks

  • Dan AbramovAlgebraic Effects for the Rest of Us on overreacted.io. The full three-step build in this article — try/catch → limitation → perform/resume with — follows Dan's progression directly. The Arya Stark example, the "resumable try/catch" framing, the "function has no color" insight about async infection, the async handler example, and the quote about Sebastian Markbåge using algebraic effects as a running joke on the React team — all come verbatim or paraphrased from this article. Read it after this one.

  • Sam GalsonMagic in the web of it (talk) and Continuations, coroutines, fibers, effects (article). The quote about how "a component is able to suspend the fiber it is running in by throwing a promise" and the throw-handle-resume pattern description come directly from Sam's article.

  • Sebastian Markbåge — for the original "Poor man's algebraic effects" gist that modeled the technique later used by React Suspense, cited in Sam Galson's article.

  • jser.dev — source verification of how throwException, the Suspense retry mechanism, and ErrorBoundary recovery actually work in the React codebase.


Part 5 is next — the React lifecycle from the inside: when useEffect and useLayoutEffect fire, and why the order is exactly what it is. 🔧


Tags: #react #javascript #webdev #tutorial