Skip to content

Commit 36a6123

Browse files
committed
move selector into component in useSelector example to fix shared selector issue; add note that warns about shared selector issues
1 parent 301a42f commit 36a6123

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

docs/api/hooks.md

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,18 +88,23 @@ import React from 'react'
8888
import { useSelector } from 'react-redux'
8989
import { createSelector } from 'reselect'
9090

91-
const allOtherTodos = createSelector(
92-
state => state.todos,
93-
(_, id) => id,
94-
(todos, id) => todos.filter(todo => todo.id !== id)
95-
)
96-
9791
export const OtherTodoListItems = ({ id }) => {
98-
const otherTodos = useSelector(s => allOtherTodos(s, id), [id])
92+
const selectAllOtherTodos = createSelector(
93+
state => state.todos,
94+
todos => todos.filter(todo => todo.id !== id)
95+
)
96+
97+
// the id in the deps ensures the same selector reference
98+
// is used on reach render as long as the id does not
99+
// change, thereby allowing the selector to memoize on
100+
// the state
101+
const otherTodos = useSelector(selectAllOtherTodos, [id])
99102
return <div>{otherTodos.length}</div>
100103
}
101104
```
102105

106+
> **Note**: When using memoizing selectors like in the example above, but declared outside the component, make sure you are [correctly handling the props](https://github.com/reduxjs/reselect#accessing-react-props-in-selectors).
107+
103108
## `useActions()`
104109

105110
```js

0 commit comments

Comments
 (0)