DEV Community

loading...

React-redux useSelector hook and equality checks

Tomasz Kudlinski
Fullstack Engineer #react #typescript #node.js #react-native #redux #graphql #apollo
・1 min read

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

Discussion (0)