Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get more than one value from the Redux store in a single statement?

I have this code:

const { user } = useSelector((state) => state.userReducer);
const { other } = useSelector((state) => state.otherReducer);

How could I get in one line those two (or more) values from the store?

const { user, other } = useSelector((state) => ?);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const { user, other } = useSelector((state) => ({ 
  user: state.userReducer,
  other: state.otherReducer
}))

If you use lodash:

import { pick, isEqual } from 'lodash-es';

const { userReducer, otherReducer } = useSelector(
  (state) => pick(state, ['userReducer', 'otherReducer']), 
  isEqual
)

The second param (isEqual) is aimed at resolving the potential performance issue mentioned by @NicholasTower (and is equivalent to react-redux‘s shallowEqual).
Without a shallow object equality function, the component will re-render every time any mutation is committed to that store, regardless of key.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading