0
# React Redux Hooks
1
2
Modern React hooks for accessing Redux store state and dispatch functions with optimal performance and type safety.
3
4
## Capabilities
5
6
### useSelector Hook
7
8
Extracts data from Redux store state with automatic re-rendering when selected data changes. Uses shallow equality by default but supports custom equality functions.
9
10
```typescript { .api }
11
/**
12
* Hook for extracting data from Redux store state
13
* @param selector - Function that receives state and returns selected data
14
* @param equalityFnOrOptions - Optional equality function or options object
15
* @returns Selected data from store state
16
*/
17
interface UseSelector<StateType = unknown> {
18
<TState extends StateType = StateType, Selected = unknown>(
19
selector: (state: TState) => Selected,
20
equalityFnOrOptions?: EqualityFn<Selected> | UseSelectorOptions<Selected>
21
): Selected;
22
23
withTypes: <OverrideStateType extends StateType>() => UseSelector<OverrideStateType>;
24
}
25
26
const useSelector: UseSelector;
27
28
interface UseSelectorOptions<Selected = unknown> {
29
equalityFn?: EqualityFn<Selected>;
30
devModeChecks?: Partial<DevModeChecks>;
31
}
32
33
type EqualityFn<T> = (a: T, b: T) => boolean;
34
```
35
36
**Usage Examples:**
37
38
```typescript
39
import { useSelector } from "react-redux";
40
41
// Basic usage
42
const todos = useSelector((state: RootState) => state.todos);
43
44
// With custom equality function
45
const todoCount = useSelector(
46
(state: RootState) => state.todos.length,
47
(prev, next) => prev === next
48
);
49
50
// With options object
51
const visibleTodos = useSelector(
52
(state: RootState) => state.todos.filter(todo => todo.visible),
53
{
54
equalityFn: (prev, next) => prev.length === next.length,
55
devModeChecks: { stabilityCheck: 'once' }
56
}
57
);
58
59
// Using pre-typed hook
60
const useAppSelector = useSelector.withTypes<RootState>();
61
const user = useAppSelector((state) => state.user); // Fully typed
62
```
63
64
### useDispatch Hook
65
66
Returns the dispatch function from the Redux store, allowing components to dispatch actions.
67
68
```typescript { .api }
69
/**
70
* Hook for accessing Redux store dispatch function
71
* @returns Dispatch function from the store
72
*/
73
interface UseDispatch<DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> {
74
<AppDispatch extends DispatchType = DispatchType>(): AppDispatch;
75
withTypes: <OverrideDispatchType extends DispatchType>() => UseDispatch<OverrideDispatchType>;
76
}
77
78
const useDispatch: UseDispatch;
79
```
80
81
**Usage Examples:**
82
83
```typescript
84
import { useDispatch } from "react-redux";
85
86
// Basic usage
87
const dispatch = useDispatch();
88
89
const handleAddTodo = (text: string) => {
90
dispatch({ type: "ADD_TODO", payload: text });
91
};
92
93
// With thunk actions
94
const handleAsyncAction = async () => {
95
dispatch(fetchUserData(userId));
96
};
97
98
// Using pre-typed hook
99
const useAppDispatch = useDispatch.withTypes<AppDispatch>();
100
const dispatch = useAppDispatch(); // Typed with thunk support
101
```
102
103
### useStore Hook
104
105
Returns the Redux store instance directly. Rarely needed as useSelector and useDispatch cover most use cases.
106
107
```typescript { .api }
108
/**
109
* Hook for accessing Redux store instance
110
* @returns The Redux store instance
111
*/
112
interface UseStore<StoreType extends Store> {
113
(): StoreType;
114
<StateType extends ReturnType<StoreType['getState']> = ReturnType<StoreType['getState']>,
115
ActionType extends Action = ExtractStoreActionType<Store>>(): Store<StateType, ActionType>;
116
withTypes: <OverrideStoreType extends StoreType>() => UseStore<OverrideStoreType>;
117
}
118
119
const useStore: UseStore<Store>;
120
121
type ExtractStoreActionType<StoreType extends Store> =
122
StoreType extends Store<any, infer ActionType> ? ActionType : never;
123
```
124
125
**Usage Examples:**
126
127
```typescript
128
import { useStore } from "react-redux";
129
130
// Basic usage
131
const store = useStore();
132
133
// Access current state directly
134
const currentState = store.getState();
135
136
// Subscribe to store changes (not recommended, use useSelector instead)
137
useEffect(() => {
138
const unsubscribe = store.subscribe(() => {
139
console.log("Store updated:", store.getState());
140
});
141
return unsubscribe;
142
}, [store]);
143
144
// Using pre-typed hook
145
const useAppStore = useStore.withTypes<AppStore>();
146
const store = useAppStore(); // Fully typed store
147
```
148
149
### Hook Factory Functions
150
151
Create custom hooks that use a different React context, useful for multiple store scenarios.
152
153
```typescript { .api }
154
/**
155
* Creates a custom useSelector hook for a specific context
156
* @param context - React context to use instead of default ReactReduxContext
157
* @returns Custom useSelector hook bound to the context
158
*/
159
function createSelectorHook<StateType = unknown>(
160
context?: Context<ReactReduxContextValue<StateType> | null>
161
): UseSelector<StateType>;
162
163
/**
164
* Creates a custom useDispatch hook for a specific context
165
* @param context - React context to use instead of default ReactReduxContext
166
* @returns Custom useDispatch hook bound to the context
167
*/
168
function createDispatchHook<StateType = unknown, ActionType extends Action = UnknownAction>(
169
context?: Context<ReactReduxContextValue<StateType, ActionType> | null>
170
): UseDispatch<Dispatch<ActionType>>;
171
172
/**
173
* Creates a custom useStore hook for a specific context
174
* @param context - React context to use instead of default ReactReduxContext
175
* @returns Custom useStore hook bound to the context
176
*/
177
function createStoreHook<StateType = unknown, ActionType extends Action = Action>(
178
context?: Context<ReactReduxContextValue<StateType, ActionType> | null>
179
): UseStore<Store<StateType, ActionType>>;
180
```
181
182
**Usage Examples:**
183
184
```typescript
185
import { createContext } from "react";
186
import { createSelectorHook, createDispatchHook, createStoreHook } from "react-redux";
187
188
// Create custom context for second store
189
const SecondaryContext = createContext(null);
190
191
// Create custom hooks
192
const useSecondarySelector = createSelectorHook(SecondaryContext);
193
const useSecondaryDispatch = createDispatchHook(SecondaryContext);
194
const useSecondaryStore = createStoreHook(SecondaryContext);
195
196
// Use in components
197
function ComponentWithSecondaryStore() {
198
const data = useSecondarySelector((state) => state.data);
199
const dispatch = useSecondaryDispatch();
200
const store = useSecondaryStore();
201
202
return <div>{data}</div>;
203
}
204
205
// Create pre-typed custom hooks with withTypes()
206
const useSecondaryAppSelector = useSecondarySelector.withTypes<SecondaryRootState>();
207
const useSecondaryAppDispatch = useSecondaryDispatch.withTypes<SecondaryAppDispatch>();
208
```
209
210
## Development Features
211
212
### Development Mode Checks
213
214
React Redux includes built-in development checks to help identify common issues:
215
216
```typescript { .api }
217
type DevModeCheckFrequency = 'never' | 'once' | 'always';
218
219
interface DevModeChecks {
220
stabilityCheck: DevModeCheckFrequency;
221
identityFunctionCheck: DevModeCheckFrequency;
222
}
223
```
224
225
- **Stability Check**: Warns when selectors return different results for the same input
226
- **Identity Function Check**: Warns when selectors return the entire state object
227
- **Frequency Options**:
228
- `'never'`: Disable the check
229
- `'once'`: Run check only once per selector
230
- `'always'`: Run check on every selector call
231
232
**Configuration:**
233
234
```typescript
235
// Configure checks in Provider
236
<Provider
237
store={store}
238
stabilityCheck="once"
239
identityFunctionCheck="always"
240
>
241
<App />
242
</Provider>
243
244
// Configure checks per selector
245
const data = useSelector(
246
(state) => state.data,
247
{ devModeChecks: { stabilityCheck: 'never' } }
248
);
249
```
250
251
### Pre-typed Hooks (.withTypes() Methods)
252
253
React Redux 9.1.0+ supports pre-typed hooks for better TypeScript developer experience:
254
255
```typescript
256
// Define your app types
257
type RootState = ReturnType<typeof store.getState>;
258
type AppDispatch = typeof store.dispatch;
259
type AppStore = typeof store;
260
261
// Create pre-typed hooks
262
export const useAppSelector = useSelector.withTypes<RootState>();
263
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
264
export const useAppStore = useStore.withTypes<AppStore>();
265
266
// Use throughout your app with full type safety
267
const todos = useAppSelector((state) => state.todos); // state is typed as RootState
268
const dispatch = useAppDispatch(); // dispatch is typed as AppDispatch
269
```