Last active
April 7, 2021 22:10
-
-
Save melbourne2991/e5c7a26fe95ec60256b8e3f946658113 to your computer and use it in GitHub Desktop.
React state context
This file contains hidden or 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, { Dispatch, createContext, useMemo, useContext } from "react"; | |
type ProviderProps<S, A> = React.PropsWithChildren<{ | |
state: S; | |
dispatch: Dispatch<A>; | |
}>; | |
type MakeStateContextReturn<S, A> = [ | |
ContextProvider: ({ state, dispatch }: ProviderProps<S, A>) => JSX.Element, | |
useContext: () => [S, Dispatch<A>] | |
]; | |
export function makeStateContext<S, A>(): MakeStateContextReturn<S, A> { | |
const Context = createContext<[S, Dispatch<A>]>(null as any); | |
const ContextProvider = ({ | |
state, | |
dispatch, | |
...rest | |
}: ProviderProps<S, A>) => { | |
return ( | |
<Context.Provider | |
value={useMemo(() => { | |
return [state, dispatch]; | |
}, [state, dispatch])} | |
{...rest} | |
/> | |
); | |
}; | |
const useContextHook = () => useContext(Context); | |
return [ContextProvider, useContextHook]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment