Reputation: 2583
I've just started playing with the new useSelector
hook provided in react-redux
.
I have always passed props directly in to my selectors like this:
mapStateToProps(state, ownProps) {
return {
user: userSelector(state, ownProps.userId)
}
}
Is passing props directly into selectors considered an anti pattern?
If "No", then how can I achieve this with useSelector
?
If "Yes", then what are the correct patterns to achieve this parameterisation of the selector?
Upvotes: 8
Views: 18561
Reputation: 11848
This is good practice to use props
in selectors.
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.
useSelector
accepts function with state
argument. If you'll pass arrow function to useSelector
you'll be able to access any variable in closure, including props
.
This example is taken from official documentation
import React from 'react'
import { useSelector } from 'react-redux'
export const TodoListItem = props => {
const todo = useSelector(state => state.todos[props.id])
return <div>{todo.text}</div>
}
Also take a look at stale props page in official documentation on how to avoid some mistakes with local props
usage.
Upvotes: 8