B
B
bzotsss2021-09-18 10:55:03
React
bzotsss, 2021-09-18 10:55:03

Why is there a re-render when changing the array in useSelector?

Hello everyone, I have a component that changes the array in redux through dispatch, to the same array

import React from 'react';
import { useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { setCountAC } from './redux/mainReducer';
const SecondComponent = () => {
    const count = useSelector(store=>store.mainInfo.count)
    const dispatch = useDispatch()
    return (
        <div onClick={() => dispatch(setCountAC([2,3,4]))}>
            {count}
        </div>
    );
}
SecondComponent.whyDidYouRender = true;
export default SecondComponent;

Here is the reducer code
const SET_COUNT = "SET_COUNT";
const initialState = {
  count:[
    1,2,3
  ]
};
export const mainReducer = (state = initialState, action) => {
  const copyState = { ...state };
  if (action.type === SET_COUNT) {
      copyState.count = [...state.count]
    return {
      ...copyState,
    };
  }
  return state;
};
export const setCountAC = (count) => ({type:SET_COUNT,count:count})

The question is, why does a re-render occur when an array changes, but not when a primitive value changes? Is it related to the fact that array = object ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2021-09-18
@bzotsss

You need to check that the arrays are not equal. Made a superficial comparison. You may also need to go deeper into the elements, but these are details. In general, compare arrays.

const isShallowEqualArrays = (arr1, arr2) =>
    arr1 === arr2 || (arr1.length === arr2.length && arr1.every((v, i) => v === arr2[i]));

export const mainReducer = (state = initialState, action) => {
    if (action.type === SET_COUNT) {
        if (!isShallowEqualArrays(state.count, action.count)) {
            return {
                ...state,
                count: action.count
            };
        }
    }
    return state;
};

V
Vladimir Lewandowski, 2021-09-18
@vovaspace

Is it related to the fact that array = object ?

Yes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question