Last active
January 26, 2020 00:34
-
-
Save arabold/923bf6a522ff20c1e9b683cf248e9550 to your computer and use it in GitHub Desktop.
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 produce, { Draft } from "immer"; | |
import { useCallback, useRef, useState } from "react"; | |
export type GetStateFunc<T> = () => Readonly<T>; | |
export type SetStateFunc<T> = (callback: T | ((draft: Draft<T>) => void)) => void; | |
/** | |
* | |
* @param initialValue | |
*/ | |
export function useImmerStore<T>(initialValue: T): [GetStateFunc<T>, SetStateFunc<T>] { | |
const [innerState, setInnerState] = useState<Readonly<T>>(initialValue); | |
const stateRef = useRef<Readonly<T>>(innerState); | |
const getState = useCallback((): Readonly<T> => stateRef.current, []); | |
const setState = useCallback( | |
(callback: T | ((draft: Draft<T>) => void)) => { | |
const nextState = | |
typeof callback === "function" ? produce(getState(), callback as (draft: Draft<T>) => void) : callback; | |
stateRef.current = nextState; | |
setInnerState(nextState); | |
}, | |
[getState], | |
); | |
return [getState, setState]; | |
} | |
export default useImmerStore; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: