Answer the question
In order to leave comments, you need to log in
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;
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})
Answer the question
In order to leave comments, you need to log in
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;
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question