Skip to content

Commit

Permalink
Update hooks.md — reselect usage with multiple instances simplified
Browse files Browse the repository at this point in the history
  • Loading branch information
VorontsovIE committed Jan 2, 2024
1 parent 8c503ef commit bc91334
Showing 1 changed file with 1 addition and 36 deletions.
37 changes: 1 addition & 36 deletions docs/api/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,42 +224,7 @@ export const App = () => {
}
```

However, when the selector is used in multiple component instances and depends on the component's props, you need to ensure that each component instance gets its own selector instance (see [here](https://github.com/reduxjs/reselect#q-can-i-share-a-selector-across-multiple-component-instances) for a more thorough explanation of why this is necessary):

```jsx
import React, { useMemo } from 'react'
import { useSelector } from 'react-redux'
import { createSelector } from 'reselect'

const makeSelectCompletedTodosCount = () =>
createSelector(
(state) => state.todos,
(_, completed) => completed,
(todos, completed) =>
todos.filter((todo) => todo.completed === completed).length
)

export const CompletedTodosCount = ({ completed }) => {
const selectCompletedTodosCount = useMemo(makeSelectCompletedTodosCount, [])

const matchingCount = useSelector((state) =>
selectCompletedTodosCount(state, completed)
)

return <div>{matchingCount}</div>
}

export const App = () => {
return (
<>
<span>Number of done todos:</span>
<CompletedTodosCount completed={true} />
<span>Number of unfinished todos:</span>
<CompletedTodosCount completed={false} />
</>
)
}
```
However, when the selector is used in multiple component instances and depends on the component's props, you need to ensure that selector's memoization behavior is properly configured (see [here](https://reselect.js.org/faq/#can-i-share-a-selector-across-multiple-component-instances) for details).

### Development mode checks

Expand Down

0 comments on commit bc91334

Please sign in to comment.