Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent redux useSelector from re-rendering

I have a component that uses React-Redux's useSelector hook to retrieve a dictionary in the Redux store. The dictionary is a map of UUIDs to objects containing data that I am rendering.

interface IComponentProps {
  id: string
}

const Component: React.FC<IComponentProps> = (props) => {
  const dataMap = useSelector((store: IRootState) => store.data.value)

  return (
    <div>
      <h1>{dataMap[props.id].title}</h1>
      <p>{dataMap[props.id].description}</p>
    </div>
  )
}

I have a dispatch method that adds a new key-value pair to the data dictionary in the redux store.

Say I have multiple of these <Component />, and another <ComponentTwo /> that dispatches the method to add a new key-value pair. When the dispatch method happens, all my <Component /> will rerender even though I don't want them as their perspective title and description stay the same. Is there a way for me to disable the rerendering?

like image 921
howranwin Avatar asked Dec 21 '25 06:12

howranwin


1 Answers

You can create a memoized selector with createSelector from Redux-Toolkit (reselect) that uses the id prop as part of its selection and result memoization process.

See How do I create a selector that takes an argument?

Example:

import { createSelector } from '@reduxjs/toolkit';
// or if not using Redux-Toolkit
// import { createSelector } from 'reselect';

export const selectDataById = createSelector(
  [
    (state: IRootState) => state.data.value,
    (state: IRootState, id: string) => id
  ],
  (dataMap, id) => dataMap[id],
);

The selectDataById selector function will only recompute its output value when either of the input selectors' value changes. If the computed output value doesn't change then consuming components should not be triggered to rerender.

import { selectDataById } from '../path/to/selectDataById';

interface IComponentProps {
  id: string
}

const Component = ({ id }: IComponentProps) => {
  const data = useSelector((state: IRootState) => selectDataById(state, id));

  // check/handle undefined data reference?

  return (
    <div>
      <h1>{data?.title}</h1>
      <p>{data?.description}</p>
    </div>
  );
};
like image 182
Drew Reese Avatar answered Dec 23 '25 23:12

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!