0
# Redux Toolkit
1
2
Redux Toolkit (RTK) is the official, opinionated, batteries-included toolset for efficient Redux development. It provides powerful utilities to simplify store setup, action creation, immutable updates, and data fetching, all with full TypeScript support and developer experience optimizations.
3
4
## Package Information
5
6
- **Package Name**: @reduxjs/toolkit
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @reduxjs/toolkit react-redux`
10
11
## Core Imports
12
13
```typescript
14
import { configureStore, createSlice, createAsyncThunk } from "@reduxjs/toolkit";
15
```
16
17
**Entry Points:**
18
- `@reduxjs/toolkit` - Core Redux Toolkit utilities
19
- `@reduxjs/toolkit/react` - React-specific enhancements
20
- `@reduxjs/toolkit/query` - RTK Query data fetching
21
- `@reduxjs/toolkit/query/react` - RTK Query React hooks
22
23
For CommonJS:
24
25
```javascript
26
const { configureStore, createSlice, createAsyncThunk } = require("@reduxjs/toolkit");
27
```
28
29
## Basic Usage
30
31
```typescript
32
import { configureStore, createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
33
34
// Define state type
35
interface CounterState {
36
value: number;
37
status: 'idle' | 'loading';
38
}
39
40
// Create async thunk
41
const incrementAsync = createAsyncThunk(
42
'counter/incrementAsync',
43
async (amount: number) => {
44
await new Promise(resolve => setTimeout(resolve, 1000));
45
return amount;
46
}
47
);
48
49
// Create slice with actions and reducer
50
const counterSlice = createSlice({
51
name: 'counter',
52
initialState: { value: 0, status: 'idle' } as CounterState,
53
reducers: {
54
increment: (state) => {
55
state.value += 1;
56
},
57
decrement: (state) => {
58
state.value -= 1;
59
},
60
incrementByAmount: (state, action: PayloadAction<number>) => {
61
state.value += action.payload;
62
}
63
},
64
extraReducers: (builder) => {
65
builder
66
.addCase(incrementAsync.pending, (state) => {
67
state.status = 'loading';
68
})
69
.addCase(incrementAsync.fulfilled, (state, action) => {
70
state.status = 'idle';
71
state.value += action.payload;
72
});
73
}
74
});
75
76
// Configure store
77
const store = configureStore({
78
reducer: {
79
counter: counterSlice.reducer
80
}
81
});
82
83
// Export actions and store
84
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
85
export { incrementAsync };
86
export default store;
87
```
88
89
## Architecture
90
91
Redux Toolkit is built around several key concepts:
92
93
- **Store Configuration**: `configureStore()` provides sensible defaults for Redux store setup with automatic middleware configuration
94
- **Slice Management**: `createSlice()` generates action creators and reducers from a single configuration object
95
- **Immutable Updates**: Built-in Immer integration enables "mutative" logic that produces immutable updates
96
- **Async Logic**: `createAsyncThunk()` handles async operations with automatic pending/fulfilled/rejected actions
97
- **Data Fetching**: RTK Query provides a complete data fetching solution with caching, invalidation, and React hooks
98
- **Type Safety**: Full TypeScript integration with extensive type inference and safety features
99
100
## Capabilities
101
102
### Store Configuration
103
104
Simplified store setup with automatic middleware configuration, Redux DevTools integration, and performance optimizations.
105
106
```typescript { .api }
107
function configureStore<S = any, A extends Action = AnyAction, M extends Middlewares<S> = Middlewares<S>, E extends Enhancers = Enhancers>(
108
options: ConfigureStoreOptions<S, A, M, E>
109
): EnhancedStore<S, A, E>;
110
111
interface ConfigureStoreOptions<S, A, M, E, P = S> {
112
reducer: Reducer<S, A> | ReducersMapObject<S, A>;
113
middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;
114
devTools?: boolean | DevToolsOptions;
115
preloadedState?: P;
116
enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<S>) => E;
117
}
118
```
119
120
[Store Configuration](./core-store.md)
121
122
### Actions & Reducers
123
124
Type-safe action creators and reducers with automatic action type generation and Immer-powered immutable updates.
125
126
```typescript { .api }
127
function createAction<P = void, T extends string = string>(
128
type: T,
129
prepareAction?: PrepareAction<P>
130
): PayloadActionCreator<P, T>;
131
132
function createSlice<
133
State,
134
CaseReducers extends SliceCaseReducers<State>,
135
Name extends string = string
136
>(options: CreateSliceOptions<State, CaseReducers, Name>): Slice<State, CaseReducers, Name>;
137
138
interface PayloadAction<P = void, T extends string = string, M = never, E = never> {
139
payload: P;
140
type: T;
141
meta?: M;
142
error?: E;
143
}
144
```
145
146
[Actions & Reducers](./actions-reducers.md)
147
148
### Async Operations
149
150
Streamlined async logic handling with automatic loading states and error management.
151
152
```typescript { .api }
153
function createAsyncThunk<
154
Returned,
155
ThunkArg = void,
156
ThunkApiConfig extends AsyncThunkConfig = {}
157
>(
158
typePrefix: string,
159
payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>,
160
options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>
161
): AsyncThunk<Returned, ThunkArg, ThunkApiConfig>;
162
163
interface AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {
164
pending: ActionCreatorWithPreparedPayload<[string, ThunkArg, AsyncThunkOptions<ThunkArg, ThunkApiConfig>?], undefined, string, never, {
165
arg: ThunkArg;
166
requestId: string;
167
requestStatus: "pending";
168
}>;
169
fulfilled: ActionCreatorWithPreparedPayload<[Returned, string, ThunkArg, AsyncThunkOptions<ThunkArg, ThunkApiConfig>?], Returned, string, never, {
170
arg: ThunkArg;
171
requestId: string;
172
requestStatus: "fulfilled";
173
}>;
174
rejected: ActionCreatorWithPreparedPayload<[unknown, string, ThunkArg, AsyncThunkOptions<ThunkArg, ThunkApiConfig>?, string?, SerializedError?], undefined, string, SerializedError, {
175
arg: ThunkArg;
176
requestId: string;
177
requestStatus: "rejected";
178
aborted?: boolean;
179
condition?: boolean;
180
}>;
181
}
182
```
183
184
[Async Operations](./async-thunks.md)
185
186
### Entity Management
187
188
Normalized state management with prebuilt CRUD operations and selectors.
189
190
```typescript { .api }
191
function createEntityAdapter<T, Id extends EntityId = EntityId>(
192
options?: {
193
selectId?: IdSelector<T, Id>;
194
sortComparer?: false | Comparer<T>;
195
}
196
): EntityAdapter<T, Id>;
197
198
interface EntityAdapter<T, Id extends EntityId> {
199
addOne<S extends EntityState<T, Id>>(state: S, entity: T): void;
200
addMany<S extends EntityState<T, Id>>(state: S, entities: readonly T[] | Record<Id, T>): void;
201
setOne<S extends EntityState<T, Id>>(state: S, entity: T): void;
202
setMany<S extends EntityState<T, Id>>(state: S, entities: readonly T[] | Record<Id, T>): void;
203
setAll<S extends EntityState<T, Id>>(state: S, entities: readonly T[] | Record<Id, T>): void;
204
removeOne<S extends EntityState<T, Id>>(state: S, key: Id): void;
205
removeMany<S extends EntityState<T, Id>>(state: S, keys: readonly Id[]): void;
206
removeAll<S extends EntityState<T, Id>>(state: S): void;
207
updateOne<S extends EntityState<T, Id>>(state: S, update: Update<T, Id>): void;
208
updateMany<S extends EntityState<T, Id>>(state: S, updates: ReadonlyArray<Update<T, Id>>): void;
209
upsertOne<S extends EntityState<T, Id>>(state: S, entity: T): void;
210
upsertMany<S extends EntityState<T, Id>>(state: S, entities: readonly T[] | Record<Id, T>): void;
211
getInitialState(): EntityState<T, Id>;
212
getInitialState<S extends Record<string, any>>(state: S): EntityState<T, Id> & S;
213
getSelectors(): EntitySelectors<T, EntityState<T, Id>, Id>;
214
getSelectors<V>(selectState: (state: V) => EntityState<T, Id>): EntitySelectors<T, V, Id>;
215
}
216
```
217
218
[Entity Management](./entity-adapters.md)
219
220
### Middleware System
221
222
Advanced middleware for side effects, dynamic middleware injection, and development-time invariants.
223
224
```typescript { .api }
225
function createListenerMiddleware<
226
StateType = unknown,
227
DispatchType extends Dispatch = AppDispatch,
228
ExtraArgument = unknown
229
>(options?: CreateListenerMiddlewareOptions<ExtraArgument>): ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;
230
231
function createDynamicMiddleware<
232
State = any,
233
DispatchType extends Dispatch<AnyAction> = Dispatch<AnyAction>
234
>(): DynamicMiddlewareInstance<State, DispatchType>;
235
```
236
237
[Middleware](./middleware.md)
238
239
### RTK Query
240
241
Complete data fetching solution with automatic caching, background updates, and optimistic updates.
242
243
```typescript { .api }
244
function createApi<
245
BaseQuery extends BaseQueryFn,
246
Definitions extends EndpointDefinitions,
247
ReducerPath extends string = 'api',
248
TagTypes extends string = never
249
>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes>;
250
251
function fetchBaseQuery(
252
options?: FetchBaseQueryArgs
253
): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError>;
254
```
255
256
[RTK Query Core](./rtk-query.md)
257
258
### React Integration
259
260
React hooks for data fetching, automatic re-rendering, and component lifecycle integration.
261
262
```typescript { .api }
263
// Auto-generated hooks for each endpoint
264
type UseQueryHook = <T = QueryResult>(
265
arg: QueryArg,
266
options?: UseQueryOptions
267
) => UseQueryResult<T>;
268
269
type UseMutationHook = <T = MutationResult>() => [
270
(arg: MutationArg) => Promise<T>,
271
MutationResult
272
];
273
274
// Provider component
275
function ApiProvider<A extends Api<any, {}, any, any>>(props: {
276
api: A;
277
setupListeners?: boolean | ((dispatch: ThunkDispatch<any, any, any>) => () => void);
278
children: React.ReactNode;
279
}): JSX.Element;
280
```
281
282
[RTK Query React](./rtk-query-react.md) | [React Integration](./react-integration.md)
283
284
### Utility Functions
285
286
Helper functions for selectors, action matching, and development utilities.
287
288
```typescript { .api }
289
function createSelector<InputSelectors extends readonly unknown[], Result>(
290
...args: [...inputSelectors: InputSelectors, resultFunc: (...args: SelectorResultArray<InputSelectors>) => Result]
291
): Selector<GetStateFromSelectors<InputSelectors>, Result>;
292
293
function isAllOf<A extends AnyAction>(
294
...matchers: readonly ActionMatcherOrType<A>[]
295
): ActionMatcher<A>;
296
297
function isAnyOf<A extends AnyAction>(
298
...matchers: readonly ActionMatcherOrType<A>[]
299
): ActionMatcher<A>;
300
301
function nanoid(size?: number): string;
302
```
303
304
[Utilities](./utilities.md)
305
306
## TypeScript Support
307
308
Redux Toolkit is written in TypeScript and provides excellent type safety out of the box:
309
310
```typescript
311
import type { PayloadAction } from '@reduxjs/toolkit';
312
import type { RootState, AppDispatch } from './store';
313
314
// Type-safe useSelector and useDispatch
315
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
316
export const useAppDispatch = () => useDispatch<AppDispatch>();
317
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
318
```
319
320
## Best Practices
321
322
- Use `createSlice()` for most reducers to automatically generate actions and handle immutable updates
323
- Prefer `createAsyncThunk()` for async logic over manual thunks
324
- Use RTK Query for data fetching to eliminate manual cache management
325
- Enable TypeScript strict mode for maximum type safety
326
- Use the Redux DevTools extension for debugging (enabled by default in `configureStore()`)
327
- Organize features using the "feature folder" approach with co-located slices