DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Tomasz Kudlinski
Tomasz Kudlinski

Posted on

React-redux useSelector hook and equality checks

useSelector is one of the redux hooks, which really makes life of a dev much more convenient. Usually we use it to get primitive type value like in below example with isLoggedIn:

import { useSelector } from 'react-redux'

const isLoggedIn = useSelector((state) => state.user.isLoggedIn)

useSelector will cause component rerender, after redux action was dispatched only if the result will be different than the last one. It checks whether it has changed based on === comparison of the result. So, if in your selector result is wrapped in the object like below:

import { useSelector } from 'react-redux'

const { isLoggedIn, numberOfUsers } = useSelector(({
    user: { isLoggedIn },
    users: { numberOfUsers }
}) => ({ isLoggedIn, numberOfUsers }))

useSelector hook will cause your component to be rerender every time an action is dispatched.

The solution for this problem is to introduce shallow comparison of the result object (result object props will be compared like in connect()), check below example:

import { shallowEqual, useSelector } from 'react-redux'

const { isLoggedIn, numberOfUsers } = useSelector(({
    user: { isLoggedIn },
    users: { numberOfUsers }
}) => ({ isLoggedIn, numberOfUsers }), shallowEqual)

Here you can ready more about it:
useSelector hook docs

Top comments (1)

Collapse
 
lijac profile image
Jacob Lee • Edited on

Valuable, thanks! Can you elaborate on when the result is wrapped in the object?

๐ŸŒš Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.