DEV Community

Discussion on: Simplify Your Redux Reducers with Immer

Collapse
swashata profile image
Swashata Ghosh

Thank you very much for this. I would like to add that I am using immer with zustand

import { create } from 'zustand';
import { redux, devtools } from 'zustand/middleware';
import { produce } from 'immer';

type MyReducerStateType = {
  count: number;
}

function myReducer(state: MyReducerStateType, action: 'increase' | 'decrease') {
  return produce(state, draftState => {
    switch (action) {
      case 'increase':
        draftState.count = state.count + 1;
        break;
      case 'decrease':
        draftState.count = state.count - 1;
        break;
      default:
        throw new Error('Invalid action type');
    }
  });
}

// create store with zustand
const [useStore] = create(devtools(redux(myReducer, {
  count: 0,
})));

// as given by redux middleware
const dispatch = useStore(store => store.dispatch);

This has drastically reduced my reducer logics.