DEV Community

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

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