Is it safe to use object destructuring to extract specific values from redux state using the useSelector() hook

Viewed 714

Would it be safe to extract specific values from the redux state using the useReducer() hook like below:

const {item1, item2, item3} = useSelector(state => state);

Or would that cause issues(with regards to rerenders and state), or be considered bad practice?

1 Answers

You should never return the entire state from a selector!

Per the docs, useSelector re-renders any time the selector return value changes after a dispatch. Therefore, it's important that each call to useSelector should return the smallest possible piece of state this component needs.

In this case, the best options are either three separate useSelector calls that each return one single field, or a single useSelector call that extracts just those fields and returns them. However, because returning a new object reference will cause a re-render, you would either need to use the shallowEqual comparison function or a memoized selector function to avoid unnecessary re-renders when returning those fields together.

Related