Home > Net >  What is immutability in Redux Toolkit and how to implement it?
What is immutability in Redux Toolkit and how to implement it?

Time:01-24

I know Immer library translates all mutable code to immutable one in createSlice() in Redux Toolkit , but I still want to write immutable reducers. Is this code immutable? If not how to correct it? What is immutability in Redux Toolkit and how to implement it?

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { Tab } from '../../logic/types'
import { TabsState, updateTabPayload } from '../types'

const initialState: TabsState = {
  tabs: []
}

export const tabsSlice = createSlice({
  name: 'tabs',
  initialState,
  reducers: {
    loadTabs: (state, tabs: PayloadAction<Tab[]>) => {
      state.tabs = [...state.tabs, ...tabs.payload]
    },
    createTab: (state, tab: PayloadAction<Tab>) => {
      state.tabs = [...state.tabs, tab.payload]
    },
    updateTab: (state, data: PayloadAction<updateTabPayload>) => {
      const index = state.tabs.findIndex((tab) => tab.id === data.payload.id)
      state.tabs[index] = { ...state.tabs[index], ...data.payload.update }
    },
    deleteTab: (state, id: PayloadAction<number>) => {
      state.tabs = state.tabs.filter((tab) => tab.id !== id.payload)
    }
  }
})

export const { loadTabs, createTab, updateTab, deleteTab } = tabsSlice.actions

export default tabsSlice.reducer

I have tried to find information about this but still don't get it.

CodePudding user response:

As soon as you write a =, it's not immutable.

An immutable update would for example look like

loadTabs: (state, tabs: PayloadAction<Tab[]>) => {
  return {
    ...state,
    tabs: [...state.tabs, ...tabs.payload],
  };
}

That said: immutability for the sake of immutability if you don't need it is an absolute fools errand.

Unless you have a good reason to need it, you should opt for writing readable code - and this is a lot harder to read, while bringing no real benefits.

You might try arguing that it is more performant, but that performance boost is absolutely neglectable. It's in the wheelhouse of "could I execute this 10 million times per second on 12 million times?".

Please do yourself a favor and write mutable createSlice case reducers. More docs here

  • Related