HackerMF
HackerMF

Reputation: 595

Redux toolkit slices. How add new array correctly?

Let's imagine a server send us array. It can be the same or not. We don't know. How to add it correctly in slice?

https://codesandbox.io/s/redux-toolkit-state-new-array-4sswi?file=/src/redux/slices/slice.js

Like this?

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

What if we get the same array? In this way actionSuccess will return like new array anyway! This means there will excess render.

So, my decision this way

const someSlice = createSlice({
  name: "someSlice",
  initialState: {
    users: []
  },
  reducers: {
    actionSuccess: (state, { payload }) => {
      if (JSON.stringify(state.users) !== JSON.stringify(payload.users)) {
        state.users = payload.users;
      }
      return state
    }
  }
});

But I think there is method better. What do u think?

Upvotes: 1

Views: 3229

Answers (1)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

I think let the redux-store get the data as it arrives from the server but use some of React's capabilities to memoize what you want.

I have forked your example and leverage React.memo in a Dumb component to show how if something new comes from the server, React will not render the Dumb component for old data because it's been memoized.

Here is the fork :-

https://codesandbox.io/s/redux-toolkit-state-new-array-forked-fgeym?file=/src/dumb.js

If you remove the React.memo bit, all the three list items will render again and again but otherwise, only the new item will render.

Check the console logs.

Note - shallow comparison by default. You can provide your custom comparison function to React.memo as second parameter.

Upvotes: 2

Related Questions