React redux toolkit. How to stop render If I get the same value? [RESOLVED]

How to stop render If I get the same value? Should I write some condition for this? Like

  if (JSON.stringify(state) === JSON.stringify(payload) {
    return state
  }
return payload

Here is a whole example

https://codesandbox.io/s/return-redux-toolkit-ersqo?file=/src/redux/slices/slice.js

here is a part of code

const someSlice = createSlice({
  name: "someSlice",
  initialState: {},
  reducers: {
    actionSuccess: (state, { payload }) => payload
  }
});

Answer

You can make use of the second argument of useSelector which is an equalityFn.

You can import shallowEqual from react-redux and pass that as second argument to the useSelector. Again this will just do shallow comparisons. You can make use of your own customised function or any library function to do a deep compairson and pass that as second argument to useSelector.

I have forked your codesandbox to showcase the shallowEqual bit :-

https://codesandbox.io/s/return-redux-toolkit-forked-wtewy

Leave a Reply

Your email address will not be published. Required fields are marked *