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