Skip to content

Instantly share code, notes, and snippets.

@melbourne2991
Last active April 7, 2021 22:10
Show Gist options
  • Save melbourne2991/e5c7a26fe95ec60256b8e3f946658113 to your computer and use it in GitHub Desktop.
Save melbourne2991/e5c7a26fe95ec60256b8e3f946658113 to your computer and use it in GitHub Desktop.
React state context
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