DEV Community

Tomasz Kudlinski
Tomasz Kudlinski

Posted on

10 4

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
lijac profile image
Jacob Lee • Edited

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay