Last Updated: November 12, 2020
·
1.151K
· StanDecaux

Proxy access to the state

So, you need to allow your components to access the state via selector. A selector is a function that has the state as a parameter, and retrieves its information. This can also allow you to select only the props needed for the component by decoupling from the state structure.

export const getUserName = ({ user: { lastName } }) => lastName
You can also pass parameters to a selector by wrapping it with a function.

export const getProduct = productId => ({ product: { list } }) =>
list.find(product => product.id === productId)
This will allow you to use them in your components using the useSelector hook.

const MyComponent = () => {
const product = useSelector(getProduct(12))
return <div>{product.name}</div>
}
It is specified in the react-redux doc that the selector is called for each render of the component. If the selector function reference does not change, a cached version of the object can be returned directly.

app/
modules/
user/
tests/
user.reducer.spec.js
components/
user.reducer.js
user.selectors.js <--- This is where all module selectors are exported

More pro tips you can find <a href="https://slashgear.github.io/react-redux-pitfalls-and-best-pratices/">Here</a>!