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

推荐订阅源

博客园 - 司徒正美
M
MIT News - Artificial intelligence
博客园_首页
IT之家
IT之家
L
LangChain Blog
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
Blog — PlanetScale
Blog — PlanetScale
人人都是产品经理
人人都是产品经理
博客园 - Franky
云风的 BLOG
云风的 BLOG
罗磊的独立博客
量子位
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
博客园 - 叶小钗
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
B
Blog
T
Tailwind CSS Blog
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

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
1 RN Thing a Day – Day 13: Redux Thunk
Ola Abaza · 2026-05-16 · via DEV Community

Ola Abaza

What Is Redux Thunk?
Redux Thunk is a middleware for Redux that allows you to write action creators that return a function instead of a plain action object.


Normally, Redux actions look like this:

{
  type: "SET_USER",
  payload: user
}

Enter fullscreen mode Exit fullscreen mode

async code doesn't work directly: Redux would throw an error because it expects an object.

dispatch(async () => { 
  const data = await api.getUser()
})

Enter fullscreen mode Exit fullscreen mode

But with thunk, you can return a function:

const fetchUser = () => {// Return an async function that receives dispatch as parameter
  return async (dispatch) => {
    const response = await api.getUser()

    dispatch({
      type: "SET_USER",
      payload: response.data
    })
  }
}

Enter fullscreen mode Exit fullscreen mode

Thunk acts as the bridge between async operations and Redux state updates.

The Problem Without Thunk
Imagine handling login directly inside a screen:

const handleLogin = async () => {
  setLoading(true)

  try {
    const response = await api.login(email, password)

    dispatch({
      type: "LOGIN_SUCCESS",
      payload: response.data
    })
  } catch (error) {
    setError(error.message)
  }

  setLoading(false)
}

Enter fullscreen mode Exit fullscreen mode

This approach causes problems:

  • Components become bloated
  • Logic is duplicated
  • Reusability decreases
  • Testing becomes harder
  • UI and business logic become tightly coupled

The Same Logic Using Thunk:

export const loginUser = (email, password) => {
  return async (dispatch) => {
    dispatch(setLoading(true))

    try {
      const response = await api.login(email, password)

      dispatch(loginSuccess(response.data))
    } catch (error) {
      dispatch(loginError(error.message))
    } finally {
      dispatch(setLoading(false))
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Then inside the component:

dispatch(loginUser(email, password))

Enter fullscreen mode Exit fullscreen mode

Now the component becomes clean and focused only on UI.


Redux Toolkit createAsyncThunk

Modern Redux apps should prefer Redux Toolkit. Instead of manually writing thunk boilerplate.

The Structure Usually:

  • Service Layer: Handles API only.
// services/userService.js

export const getProducts = async () => {
  const response = await fetch(API_URL)

  return response.json()
}

Enter fullscreen mode Exit fullscreen mode

  • Thunk Layer: Handles async Redux logic.
// store/thunks/userThunk.js

export const fetchProducts = createAsyncThunk(
  "products/fetchProducts", // action type prefix. // sliceName/actionName

  async () => {
    return await getProducts()
  }
)

Enter fullscreen mode Exit fullscreen mode

"products/fetchProducts" It is simply:a unique Redux action identifier prefix used to generate async action types automatically.

  • Slice Layer: Handles state updates.
import { createSlice } from "@reduxjs/toolkit"
import { fetchProducts } from "./productThunk"

const productSlice = createSlice({
  name: "products",

  initialState: {
    products: [],
    loading: false,
    error: null
  },

  reducers: {},

  extraReducers: (builder) => {
    builder
      .addCase(fetchProducts.pending, (state) => { /
        state.loading = true
      })

      .addCase(fetchProducts.fulfilled, (state, action) => {
//internally matches:products/fetchProducts/fulfilled
        state.loading = false
        state.products = action.payload
      })

      .addCase(fetchProducts.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message
      })
  }
})

export default productSlice.reducer

Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Cleaner syntax
  • Built-in pending/fulfilled/rejected states
  • Less boilerplate
  • Better TypeScript support

Important Concept
createAsyncThunk is NOT mainly about API calls.
It is about:
Managing async operations that affect global state. API calls are just the most common example.

Better understanding:
Thunk = async business logic connected to Redux state

That business logic may include:

  • API calls
  • caching
  • conditional fetching
  • retries
  • authentication
  • reading current state
  • dispatching multiple actions