Created
March 17, 2021 19:53
-
-
Save Pocket-titan/608f262693fac8a955a4fa4ff8b8a064 to your computer and use it in GitHub Desktop.
immer + useState = useImmerState
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 { useCallback, useState } from "react"; | |
import produce, { Draft } from "immer"; | |
function useImmerState<S = undefined>(initialState: S | (() => S)) { | |
const [state, _setState] = useState(initialState); | |
const setState = useCallback((mutateFn: (draft: Draft<S>) => S | void) => { | |
_setState(produce(mutateFn) as (oldState: S) => S); | |
}, []); | |
return [state, setState] as const; | |
} | |
export default useImmerState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment