Skip to content

Instantly share code, notes, and snippets.

@revskill10
Forked from aweary/App.js
Created October 25, 2018 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save revskill10/8d20b65cda7b033d880c8114978707c1 to your computer and use it in GitHub Desktop.
Save revskill10/8d20b65cda7b033d880c8114978707c1 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