I am trying to use a map
inside useSelector
. Is there any restrictions or good coding practice that prohibits the use of it?
const { items } = useSelector((state: any) => ({
items: state.appReducer.items.map((item: any) => {
return { itemID: item.id, itemDescription: item.desc }
})
}))
CodePudding user response:
That's a useSelector and not a useEffect.
For using map
inside hooks, it's just a looping executing a synchronous callback function. So, there is nothing to worry about here.
CodePudding user response:
You can, but your selector is buggy. useSelector
will run your selector after every dispatched action, and force the component to re-render whenever the selector returns a new value reference:
Your selector is always returning a new object, and so it will always cause this component to re-render, even if the relevant data in the store didn't change.
I'd recommend reading through these sections of the Redux docs to understand how to write selectors that will perform better:
- https://redux.js.org/usage/deriving-data-selectors
- https://redux.js.org/tutorials/fundamentals/part-5-ui-react#react-redux-patterns
- https://redux.js.org/tutorials/fundamentals/part-7-standard-patterns#memoized-selectors
- https://redux.js.org/tutorials/essentials/part-6-performance-normalization#improving-render-performance