Skip to content

Commit

Permalink
Merge pull request #2118 from aryaemami59/fix-docs
Browse files Browse the repository at this point in the history
Add `withTypes` vs previous typed-hooks comparison to docs
  • Loading branch information
Bee1130 authored and Bee1028 committed Jan 12, 2024
2 parents a674a43 + 027c290 commit 340bff8
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions docs/using-react-redux/usage-with-typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,36 @@ While it's possible to import the `RootState` and `AppDispatch` types into each
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.
#### `.withTypes()`
Previously, the approach for "pre-typing" hooks with your app setting was a little varied. The result would look something like the snippet below:
```ts title="app/hooks.ts"
import type { TypedUseSelectorHook } from 'react-redux'
import { useDispatch, useSelector, useStore } from 'react-redux'
import type { AppDispatch, AppStore, RootState } from './store'

// highlight-start
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
export const useAppStore: () => AppStore = useStore
// highlight-end
```

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`.

The setup now becomes:

```ts title="app/hooks.ts"
import { useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'
import { useDispatch, useSelector, useStore } from 'react-redux'
import type { AppDispatch, AppStore, RootState } from './store'

// highlight-start
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()
export const useAppStore = useStore.withTypes<AppStore>()
// highlight-end
```

Expand Down

0 comments on commit 340bff8

Please sign in to comment.