This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
</> | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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