Skip to content

Commit

Permalink
Update hooks docs with TS types and better descriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed Jun 6, 2023
1 parent ac122db commit ebfaf5c
Showing 1 changed file with 60 additions and 27 deletions.
87 changes: 60 additions & 27 deletions docs/api/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,24 @@ From there, you may import any of the listed React Redux hooks APIs and use them

## `useSelector()`

```js
const result: any = useSelector(selector: Function, equalityFn?: Function)
```ts
type RootState = ReturnType<typeof store.getState>
type SelectorFn = <Selected>(state: RootState) => Selected
type EqualityFn = (a: any, b: any) => boolean
export type StabilityCheck = 'never' | 'once' | 'always'

interface UseSelectorOptions {
equalityFn?: EqualityFn
stabilityCheck?: StabilityCheck
}

const result: Selected = useSelector(
selector: SelectorFunction,
options?: EqualityFn | UseSelectorOptions
)
```

Allows you to extract data from the Redux store state, using a selector function.
Allows you to extract data from the Redux store state for use in this component, using a selector function.

:::info

Expand All @@ -58,24 +71,22 @@ See [Using Redux: Deriving Data with Selectors](https://redux.js.org/usage/deriv

:::

The selector is approximately equivalent to the [`mapStateToProps` argument to `connect`](../using-react-redux/connect-extracting-data-with-mapStateToProps.md) conceptually. The selector will be called with the entire Redux store state as its only argument. The selector will be run whenever the function component renders (unless its reference hasn't changed since a previous render of the component so that a cached result can be returned by the hook without re-running the selector). `useSelector()` will also subscribe to the Redux store, and run your selector whenever an action is dispatched.
The selector will be called with the entire Redux store state as its only argument. The selector may return any value as a result, including directly returning a value that was nested inside `state`, or deriving new values. The return value of the selector will be used as the return value of the `useSelector()` hook.

The selector will be run whenever the function component renders (unless its reference hasn't changed since a previous render of the component so that a cached result can be returned by the hook without re-running the selector). `useSelector()` will also subscribe to the Redux store, and run your selector whenever an action is dispatched.

When an action is dispatched, `useSelector()` will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render. `useSelector()` uses strict `===` reference equality checks by default, not shallow equality (see the following section for more details).

However, there are some differences between the selectors passed to `useSelector()` and a `mapState` function:
The selector is approximately equivalent to the [`mapStateToProps` argument to `connect`](../using-react-redux/connect-extracting-data-with-mapStateToProps.md) conceptually.

- The selector may return any value as a result, not just an object. The return value of the selector will be used as the return value of the `useSelector()` hook.
- When an action is dispatched, `useSelector()` will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render.
- The selector function does _not_ receive an `ownProps` argument. However, props can be used through closure (see the examples below) or by using a curried selector.
- Extra care must be taken when using memoizing selectors (see examples below for more details).
- `useSelector()` uses strict `===` reference equality checks by default, not shallow equality (see the following section for more details).
You may call `useSelector()` multiple times within a single function component. Each call to `useSelector()` creates an individual subscription to the Redux store. Because of the React update batching behavior used in React Redux v7, a dispatched action that causes multiple `useSelector()`s in the same component to return new values _should_ only result in a single re-render.

:::info

There are potential edge cases with using props in selectors that may cause issues. See the [Usage Warnings](#usage-warnings) section of this page for further details.

:::

You may call `useSelector()` multiple times within a single function component. Each call to `useSelector()` creates an individual subscription to the Redux store. Because of the React update batching behavior used in React Redux v7, a dispatched action that causes multiple `useSelector()`s in the same component to return new values _should_ only result in a single re-render.

### Equality Comparisons and Updates

When the function component renders, the provided selector function will be called and its result will be returned
Expand All @@ -98,10 +109,10 @@ every time will _always_ force a re-render by default. If you want to retrieve m
```js
import { shallowEqual, useSelector } from 'react-redux'

// later
// Pass it as the second argument directly
const selectedData = useSelector(selectorReturningObject, shallowEqual)

// or with object format
// or pass it as the `equalityFn` field in the options argument
const selectedData = useSelector(selectorReturningObject, {
equalityFn: shallowEqual,
})
Expand Down Expand Up @@ -249,15 +260,23 @@ export const App = () => {

### Development mode checks

`useSelector` runs some extra checks in development mode to watch for unexpected behavior. These checks do not run in production builds.

:::info

These checks were first added in v8.1.0

:::

#### Selector result stability

In development, an extra check is conducted on the passed selector. It runs the selector an extra time with the same parameter, and warns in console if it returns a different result (based on the `equalityFn` provided).
In development, the provided selector function is run an extra time with the same parameter during the first call to `useSelector`, and warns in the console if the selector returns a different result (based on the `equalityFn` provided).

This is important, as a selector returning a materially different result with the same parameter will cause unnecessary rerenders.
This is important, as a selector returning that returns a different result reference with the same parameter will cause unnecessary rerenders.

```ts
// this selector will return a new object reference whenever called
// meaning the component will rerender whenever *any* action is dispatched
// this selector will return a new object reference whenever called,
// which causes the component to rerender after *every* action is dispatched
const { count, user } = useSelector((state) => ({
count: state.count,
user: state.user,
Expand All @@ -283,14 +302,20 @@ function Component() {
}
```

:::info
This check is disabled for production environments.
:::
### Comparisons with `connect`

There are some differences between the selectors passed to `useSelector()` and a `mapState` function:

- The selector may return any value as a result, not just an object.
- The selector normally _should_ return just a single value, and not an object. If you do return an object or an array, be sure to use a memoized selector to avoid unnecessary re-renders.
- The selector function does _not_ receive an `ownProps` argument. However, props can be used through closure (see the examples above) or by using a curried selector.
- You can use the `equalityFn` option to customize the comparison behavior

## `useDispatch()`

```js
const dispatch = useDispatch()
```ts
import type { Dispatch } from 'redux'
const dispatch: Dispatch = useDispatch()
```

This hook returns a reference to the `dispatch` function from the Redux store. You may use it to dispatch actions as needed.
Expand Down Expand Up @@ -366,8 +391,9 @@ export const Todos = () => {

## `useStore()`

```js
const store = useStore()
```ts
import type { Store } from 'redux'
const store: Store = useStore()
```

This hook returns a reference to the same Redux store that was passed in to the `<Provider>` component.
Expand All @@ -380,12 +406,19 @@ This hook should probably not be used frequently. Prefer `useSelector()` as your
import React from 'react'
import { useStore } from 'react-redux'

export const CounterComponent = ({ value }) => {
export const ExampleComponent = ({ value }) => {
const store = useStore()

const onClick = () => {
// Not _recommended_, but safe
// This avoids subscribing to the state via `useSelector`
// Prefer moving this logic into a thunk instead
const numTodos = store.getState().todos.length
}

// EXAMPLE ONLY! Do not do this in a real app.
// The component will not automatically update if the store state changes
return <div>{store.getState()}</div>
return <div>{store.getState().todos.length}</div>
}
```

Expand Down

0 comments on commit ebfaf5c

Please sign in to comment.