Skip to content

Instantly share code, notes, and snippets.

@aweary
Last active August 29, 2021 14:06
  • Star 28 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
import React from "react";
import useMutableReducer from "./useMutableReducer";
const reducer = (draft, action, state) => {
switch (action) {
case "increment":
draft.count++;
break;
case "decrement":
draft.count--;
}
};
const App = () => {
const [state, dispatch] = useMutableReducer(reducer, { count: 0 });
return (
<>
<h1>{state.count}</h1>
<button onClick={() => dispatch("increment")}>+</button>
<button onClick={() => dispatch("decrement")}>-</button>
</>
);
};
import {useReducer, useCallback} from 'react';
import {produce} from 'immer';
function useMutableReducer(reducer, initialState, initialAction) {
const mutableReducer = useCallback(
(state, action) => {
return produce(draft => {
return reducer(draft, action, state);
});
},
[reducer]
);
return useReducer(mutableReducer, initialState, initialAction);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment