Skip to content

Instantly share code, notes, and snippets.

@cheapsteak
Created April 30, 2020 20:06
Show Gist options
  • Save cheapsteak/2a2d41de11a35446097afb783e83262d to your computer and use it in GitHub Desktop.
Save cheapsteak/2a2d41de11a35446097afb783e83262d to your computer and use it in GitHub Desktop.
import React from 'react';
// Create the hook that contains state as you normally would, don't worry about context
// Note that this is _not_ exported
const useSomeState = () => {
const [someState, setSomeState] = React.useState();
return {
someState,
setSomeState,
};
};
// Use ReturnType to infer what the useSomeState hook returns
// https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypet
// This is also not exported
const SomeContext = React.createContext<ReturnType<
typeof useSomeState
> | null>(null);
// Export a provider where the value is always supplied
export const SomeContextProvider: React.FC<{
children: React.ReactNode;
}> = ({ children }) => {
const someContextValue = useSomeState();
return (
<SomeContext.Provider value={someContextValue}>
{children}
</SomeContext.Provider>
);
};
// Export a hook that consumes the above provider
// Throw if context was not found
export const useSomeContext = () => {
const context = React.useContext(SomeContext);
if (!context) {
throw new Error(
'useSomeContext must be used within a SomeContextProvider',
);
}
return context;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment