Skip to content

Instantly share code, notes, and snippets.

@aweary
Last active August 29, 2021 14:06
Show Gist options
  • Save aweary/be8338a211e72b9f1563d75091005c0e to your computer and use it in GitHub Desktop.
Save aweary/be8338a211e72b9f1563d75091005c0e to your computer and use it in GitHub Desktop.
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