Skip to content

Commit 9ce28ab

Browse files
authored
Merge pull request #2118 from aryaemami59/fix-docs
Add `withTypes` vs previous typed-hooks comparison to docs
2 parents 4ebe6e9 + 6667e27 commit 9ce28ab

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

docs/using-react-redux/usage-with-typescript.md

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,36 @@ While it's possible to import the `RootState` and `AppDispatch` types into each
6363
6464
Since these are actual variables, not types, it's important to define them in a separate file such as `app/hooks.ts`, not the store setup file. This allows you to import them into any component file that needs to use the hooks, and avoids potential circular import dependency issues.
6565
66+
#### `.withTypes()`
67+
68+
Previously, the approach for "pre-typing" hooks with your app setting was a little varied. The result would look something like the snippet below:
69+
70+
```ts title="app/hooks.ts"
71+
import type { TypedUseSelectorHook } from 'react-redux'
72+
import { useDispatch, useSelector, useStore } from 'react-redux'
73+
import type { AppDispatch, AppStore, RootState } from './store'
74+
75+
// highlight-start
76+
// Use throughout your app instead of plain `useDispatch` and `useSelector`
77+
export const useAppDispatch: () => AppDispatch = useDispatch
78+
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
79+
export const useAppStore: () => AppStore = useStore
80+
// highlight-end
81+
```
82+
83+
React Redux v9.1.0 adds a new `.withTypes` method to each of these hooks, analogous to the [`.withTypes`](https://redux-toolkit.js.org/usage/usage-with-typescript#defining-a-pre-typed-createasyncthunk) method found on Redux Toolkit's `createAsyncThunk`.
84+
85+
The setup now becomes:
86+
6687
```ts title="app/hooks.ts"
67-
import { useDispatch, useSelector } from 'react-redux'
68-
import type { RootState, AppDispatch } from './store'
88+
import { useDispatch, useSelector, useStore } from 'react-redux'
89+
import type { AppDispatch, AppStore, RootState } from './store'
6990

7091
// highlight-start
7192
// Use throughout your app instead of plain `useDispatch` and `useSelector`
7293
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
7394
export const useAppSelector = useSelector.withTypes<RootState>()
95+
export const useAppStore = useStore.withTypes<AppStore>()
7496
// highlight-end
7597
```
7698

0 commit comments

Comments
 (0)