Skip to content

Usage with immutable libraries (mutative) #135

@IrvingArmenta

Description

@IrvingArmenta

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions