Skip to content

Instantly share code, notes, and snippets.

@Pocket-titan
Created March 17, 2021 19:53
Show Gist options
  • Save Pocket-titan/608f262693fac8a955a4fa4ff8b8a064 to your computer and use it in GitHub Desktop.
Save Pocket-titan/608f262693fac8a955a4fa4ff8b8a064 to your computer and use it in GitHub Desktop.
immer + useState = useImmerState
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