[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-3793":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":15,"stars30d":15,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":16,"rankGlobal":9,"rankLanguage":9,"license":17,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":18,"hasPages":18,"topics":20,"createdAt":9,"pushedAt":9,"updatedAt":21,"readmeContent":22,"aiSummary":23,"trendingCount":15,"starSnapshotCount":15,"syncStatus":24,"lastSyncTime":25,"discoverSource":26},3793,"redux-thunk","reduxjs\u002Fredux-thunk","reduxjs","Thunk middleware for Redux",null,"TypeScript",17696,1019,164,1,0,44.03,"MIT License",false,"master",[],"2026-06-12 02:00:54","# Redux Thunk\n\nThunk [middleware](https:\u002F\u002Fredux.js.org\u002Ftutorials\u002Ffundamentals\u002Fpart-4-store#middleware) for Redux. It allows writing functions with logic inside that can interact with a Redux store's `dispatch` and `getState` methods.\n\nFor complete usage instructions and useful patterns, see the [Redux docs **Writing Logic with Thunks** page](https:\u002F\u002Fredux.js.org\u002Fusage\u002Fwriting-logic-thunks).\n\n![GitHub Workflow Status](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Factions\u002Fworkflow\u002Fstatus\u002Freduxjs\u002Fredux-thunk\u002Ftest.yml?branch=master)\n[![npm version](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002Fredux-thunk.svg?style=flat-square)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fredux-thunk)\n[![npm downloads](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fdm\u002Fredux-thunk.svg?style=flat-square)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fredux-thunk)\n\n## Installation and Setup\n\n### Redux Toolkit\n\nIf you're using [our official Redux Toolkit package](https:\u002F\u002Fredux-toolkit.js.org) as recommended, there's nothing to install - RTK's `configureStore` API already adds the thunk middleware by default:\n\n```js\nimport { configureStore } from '@reduxjs\u002Ftoolkit'\n\nimport todosReducer from '.\u002Ffeatures\u002Ftodos\u002FtodosSlice'\nimport filtersReducer from '.\u002Ffeatures\u002Ffilters\u002FfiltersSlice'\n\nconst store = configureStore({\n  reducer: {\n    todos: todosReducer,\n    filters: filtersReducer,\n  },\n})\n\n\u002F\u002F The thunk middleware was automatically added\n```\n\n### Manual Setup\n\nIf you're using the basic Redux `createStore` API and need to set this up manually, first add the `redux-thunk` package:\n\n```sh\nnpm install redux-thunk\n\nyarn add redux-thunk\n```\n\nThe thunk middleware is a named export.\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>More Details: Importing the thunk middleware\u003C\u002Fb>\u003C\u002Fsummary>\n\nIf you're using ES modules:\n\n```js\nimport { thunk } from 'redux-thunk'\n```\n\nIf you use Redux Thunk in a CommonJS environment:\n\n```js\nconst { thunk } = require('redux-thunk')\n```\n\n\u003C\u002Fdetails>\n\nThen, to enable Redux Thunk, use\n[`applyMiddleware()`](https:\u002F\u002Fredux.js.org\u002Fapi\u002Fapplymiddleware):\n\n```js\nimport { createStore, applyMiddleware } from 'redux'\nimport { thunk } from 'redux-thunk'\nimport rootReducer from '.\u002Freducers\u002Findex'\n\nconst store = createStore(rootReducer, applyMiddleware(thunk))\n```\n\n### Injecting a Custom Argument\n\nSince 2.1.0, Redux Thunk supports injecting a custom argument into the thunk middleware. This is typically useful for cases like using an API service layer that could be swapped out for a mock service in tests.\n\nFor Redux Toolkit, the `getDefaultMiddleware` callback inside of `configureStore` lets you pass in a custom `extraArgument`:\n\n```js\nimport { configureStore } from '@reduxjs\u002Ftoolkit'\nimport rootReducer from '.\u002Freducer'\nimport { myCustomApiService } from '.\u002Fapi'\n\nconst store = configureStore({\n  reducer: rootReducer,\n  middleware: getDefaultMiddleware =>\n    getDefaultMiddleware({\n      thunk: {\n        extraArgument: myCustomApiService,\n      },\n    }),\n})\n\n\u002F\u002F later\nfunction fetchUser(id) {\n  \u002F\u002F The `extraArgument` is the third arg for thunk functions\n  return (dispatch, getState, api) => {\n    \u002F\u002F you can use api here\n  }\n}\n```\n\nIf you need to pass in multiple values, combine them into a single object:\n\n```js\nconst store = configureStore({\n  reducer: rootReducer,\n  middleware: getDefaultMiddleware =>\n    getDefaultMiddleware({\n      thunk: {\n        extraArgument: {\n          api: myCustomApiService,\n          otherValue: 42,\n        },\n      },\n    }),\n})\n\n\u002F\u002F later\nfunction fetchUser(id) {\n  return (dispatch, getState, { api, otherValue }) => {\n    \u002F\u002F you can use api and something else here\n  }\n}\n```\n\nIf you're setting up the store by hand, the named export `withExtraArgument()` function should be used to generate the correct thunk middleware:\n\n```js\nconst store = createStore(reducer, applyMiddleware(withExtraArgument(api)))\n```\n\n## Why Do I Need This?\n\nWith a plain basic Redux store, you can only do simple synchronous updates by\ndispatching an action. Middleware extends the store's abilities, and lets you\nwrite async logic that interacts with the store.\n\nThunks are the recommended middleware for basic Redux side effects logic,\nincluding complex synchronous logic that needs access to the store, and simple\nasync logic like AJAX requests.\n\nFor more details on why thunks are useful, see:\n\n- **Redux docs: Writing Logic with Thunks**  \n  https:\u002F\u002Fredux.js.org\u002Fusage\u002Fwriting-logic-thunks  \n  The official usage guide page on thunks. Covers why they exist, how the thunk middleware works, and useful patterns for using thunks.\n\n- **Stack Overflow: Dispatching Redux Actions with a Timeout**  \n  http:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F35411423\u002Fhow-to-dispatch-a-redux-action-with-a-timeout\u002F35415559#35415559  \n  Dan Abramov explains the basics of managing async behavior in Redux, walking\n  through a progressive series of approaches (inline async calls, async action\n  creators, thunk middleware).\n\n- **Stack Overflow: Why do we need middleware for async flow in Redux?**  \n  http:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F34570758\u002Fwhy-do-we-need-middleware-for-async-flow-in-redux\u002F34599594#34599594  \n  Dan Abramov gives reasons for using thunks and async middleware, and some\n  useful patterns for using thunks.\n\n- **What the heck is a \"thunk\"?**  \n  https:\u002F\u002Fdaveceddia.com\u002Fwhat-is-a-thunk\u002F  \n  A quick explanation for what the word \"thunk\" means in general, and for Redux\n  specifically.\n\n- **Thunks in Redux: The Basics**  \n  https:\u002F\u002Fmedium.com\u002Ffullstack-academy\u002Fthunks-in-redux-the-basics-85e538a3fe60  \n  A detailed look at what thunks are, what they solve, and how to use them.\n\nYou may also want to read the\n**[Redux FAQ entry on choosing which async middleware to use](https:\u002F\u002Fredux.js.org\u002Ffaq\u002Factions#what-async-middleware-should-i-use-how-do-you-decide-between-thunks-sagas-observables-or-something-else)**.\n\nWhile the thunk middleware is not directly included with the Redux core library,\nit is used by default in our\n**[`@reduxjs\u002Ftoolkit` package](https:\u002F\u002Fgithub.com\u002Freduxjs\u002Fredux-toolkit)**.\n\n## Motivation\n\nRedux Thunk [middleware](https:\u002F\u002Fredux.js.org\u002Ftutorials\u002Ffundamentals\u002Fpart-4-store#middleware)\nallows you to write action creators that return a function instead of an action.\nThe thunk can be used to delay the dispatch of an action, or to dispatch only if\na certain condition is met. The inner function receives the store methods\n`dispatch` and `getState` as parameters.\n\nAn action creator that returns a function to perform asynchronous dispatch:\n\n```js\nconst INCREMENT_COUNTER = 'INCREMENT_COUNTER'\n\nfunction increment() {\n  return {\n    type: INCREMENT_COUNTER,\n  }\n}\n\nfunction incrementAsync() {\n  return dispatch => {\n    setTimeout(() => {\n      \u002F\u002F Yay! Can invoke sync or async actions with `dispatch`\n      dispatch(increment())\n    }, 1000)\n  }\n}\n```\n\nAn action creator that returns a function to perform conditional dispatch:\n\n```js\nfunction incrementIfOdd() {\n  return (dispatch, getState) => {\n    const { counter } = getState()\n\n    if (counter % 2 === 0) {\n      return\n    }\n\n    dispatch(increment())\n  }\n}\n```\n\n## What’s a thunk?!\n\nA [thunk](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FThunk) is a function that wraps an\nexpression to delay its evaluation.\n\n```js\n\u002F\u002F calculation of 1 + 2 is immediate\n\u002F\u002F x === 3\nlet x = 1 + 2\n\n\u002F\u002F calculation of 1 + 2 is delayed\n\u002F\u002F foo can be called later to perform the calculation\n\u002F\u002F foo is a thunk!\nlet foo = () => 1 + 2\n```\n\nThe term [originated](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FThunk#cite_note-1) as a\nhumorous past-tense version of \"think\".\n\n## Composition\n\nAny return value from the inner function will be available as the return value\nof `dispatch` itself. This is convenient for orchestrating an asynchronous\ncontrol flow with thunk action creators dispatching each other and returning\nPromises to wait for each other’s completion:\n\n```js\nimport { createStore, applyMiddleware } from 'redux'\nimport { thunk } from 'redux-thunk'\nimport rootReducer from '.\u002Freducers'\n\n\u002F\u002F Note: this API requires redux@>=3.1.0\nconst store = createStore(rootReducer, applyMiddleware(thunk))\n\nfunction fetchSecretSauce() {\n  return fetch('https:\u002F\u002Fwww.google.com\u002Fsearch?q=secret+sauce')\n}\n\n\u002F\u002F These are the normal action creators you have seen so far.\n\u002F\u002F The actions they return can be dispatched without any middleware.\n\u002F\u002F However, they only express “facts” and not the “async flow”.\n\nfunction makeASandwich(forPerson, secretSauce) {\n  return {\n    type: 'MAKE_SANDWICH',\n    forPerson,\n    secretSauce,\n  }\n}\n\nfunction apologize(fromPerson, toPerson, error) {\n  return {\n    type: 'APOLOGIZE',\n    fromPerson,\n    toPerson,\n    error,\n  }\n}\n\nfunction withdrawMoney(amount) {\n  return {\n    type: 'WITHDRAW',\n    amount,\n  }\n}\n\n\u002F\u002F Even without middleware, you can dispatch an action:\nstore.dispatch(withdrawMoney(100))\n\n\u002F\u002F But what do you do when you need to start an asynchronous action,\n\u002F\u002F such as an API call, or a router transition?\n\n\u002F\u002F Meet thunks.\n\u002F\u002F A thunk in this context is a function that can be dispatched to perform async\n\u002F\u002F activity and can dispatch actions and read state.\n\u002F\u002F This is an action creator that returns a thunk:\nfunction makeASandwichWithSecretSauce(forPerson) {\n  \u002F\u002F We can invert control here by returning a function - the \"thunk\".\n  \u002F\u002F When this function is passed to `dispatch`, the thunk middleware will intercept it,\n  \u002F\u002F and call it with `dispatch` and `getState` as arguments.\n  \u002F\u002F This gives the thunk function the ability to run some logic, and still interact with the store.\n  return function (dispatch) {\n    return fetchSecretSauce().then(\n      sauce => dispatch(makeASandwich(forPerson, sauce)),\n      error => dispatch(apologize('The Sandwich Shop', forPerson, error)),\n    )\n  }\n}\n\n\u002F\u002F Thunk middleware lets me dispatch thunk async actions\n\u002F\u002F as if they were actions!\n\nstore.dispatch(makeASandwichWithSecretSauce('Me'))\n\n\u002F\u002F It even takes care to return the thunk’s return value\n\u002F\u002F from the dispatch, so I can chain Promises as long as I return them.\n\nstore.dispatch(makeASandwichWithSecretSauce('My partner')).then(() => {\n  console.log('Done!')\n})\n\n\u002F\u002F In fact I can write action creators that dispatch\n\u002F\u002F actions and async actions from other action creators,\n\u002F\u002F and I can build my control flow with Promises.\n\nfunction makeSandwichesForEverybody() {\n  return function (dispatch, getState) {\n    if (!getState().sandwiches.isShopOpen) {\n      \u002F\u002F You don’t have to return Promises, but it’s a handy convention\n      \u002F\u002F so the caller can always call .then() on async dispatch result.\n\n      return Promise.resolve()\n    }\n\n    \u002F\u002F We can dispatch both plain object actions and other thunks,\n    \u002F\u002F which lets us compose the asynchronous actions in a single flow.\n\n    return dispatch(makeASandwichWithSecretSauce('My Grandma'))\n      .then(() =>\n        Promise.all([\n          dispatch(makeASandwichWithSecretSauce('Me')),\n          dispatch(makeASandwichWithSecretSauce('My wife')),\n        ]),\n      )\n      .then(() => dispatch(makeASandwichWithSecretSauce('Our kids')))\n      .then(() =>\n        dispatch(\n          getState().myMoney > 42\n            ? withdrawMoney(42)\n            : apologize('Me', 'The Sandwich Shop'),\n        ),\n      )\n  }\n}\n\n\u002F\u002F This is very useful for server side rendering, because I can wait\n\u002F\u002F until data is available, then synchronously render the app.\n\nstore\n  .dispatch(makeSandwichesForEverybody())\n  .then(() =>\n    response.send(ReactDOMServer.renderToString(\u003CMyApp store={store} \u002F>)),\n  )\n\n\u002F\u002F I can also dispatch a thunk async action from a component\n\u002F\u002F any time its props change to load the missing data.\n\nimport { connect } from 'react-redux'\nimport { Component } from 'react'\n\nclass SandwichShop extends Component {\n  componentDidMount() {\n    this.props.dispatch(makeASandwichWithSecretSauce(this.props.forPerson))\n  }\n\n  componentDidUpdate(prevProps) {\n    if (prevProps.forPerson !== this.props.forPerson) {\n      this.props.dispatch(makeASandwichWithSecretSauce(this.props.forPerson))\n    }\n  }\n\n  render() {\n    return \u003Cp>{this.props.sandwiches.join('mustard')}\u003C\u002Fp>\n  }\n}\n\nexport default connect(state => ({\n  sandwiches: state.sandwiches,\n}))(SandwichShop)\n```\n\n## License\n\nMIT\n","Redux Thunk 是一个用于 Redux 的中间件，它允许开发者编写包含逻辑的函数，这些函数可以与 Redux store 的 `dispatch` 和 `getState` 方法进行交互。其核心功能在于支持异步操作以及复杂的业务逻辑处理，使得状态管理更加灵活高效。使用 TypeScript 编写，确保了代码的类型安全性和可维护性。适用于需要在 Redux 应用中执行异步操作、访问外部 API 或者根据当前应用状态决定下一步动作的各种场景。无论是通过 Redux Toolkit 自动配置还是手动设置，都能轻松集成到项目中。",2,"2026-06-11 02:56:20","top_language"]