use-context-selector icon indicating copy to clipboard operation
use-context-selector copied to clipboard

Usage with immutable libraries (mutative)

Open IrvingArmenta opened this issue 1 year ago • 1 comments

I would like to use mutative -> https://github.com/mutativejs/use-mutative useMutativeReducer to use and update the reducer for the context

const Provider = ({ children }: { children: ReactNode }) => {
  const [state, dispatch] = useMutativeReducer(reducer, initialState);

  return (
    <context.Provider value={[state, dispatch]}>{children}</context.Provider>
  );
};

The reducer looks something like this:

export const reducer = (draft: State, action: Actions) => {
  switch (action.type) {
    case 'increment':
      draft.count++;
      break;
    case 'decrement':
      draft.count--;
      break;
    case 'setText':
      draft.text = action.payload.text;
      break;
    case 'addTodo': {
      const newLength = draft.todos.length++;
      draft.todos[newLength] = action.payload;
      break;
    }
    case 'setError': {
      draft.error = action.payload;
      break;
    }
    case 'setLoading':
      draft.loading = action.payload;
      break;
    default:
      throw new Error(`unknown action type: ${(action as Actions).type}`);
  }
};

Question

Is there any performance or possible breaking implementation issue by using something like this?

Immer would be another example of this kind of library.

IrvingArmenta avatar Sep 02 '24 01:09 IrvingArmenta