Skip to content

Instantly share code, notes, and snippets.

@louis-young
Created February 24, 2023 09:47
Show Gist options
  • Save louis-young/138f77a1274c84952717c9a31c69a583 to your computer and use it in GitHub Desktop.
Save louis-young/138f77a1274c84952717c9a31c69a583 to your computer and use it in GitHub Desktop.
Safe context hook creator function
import { type Context, useContext } from "react";
import { invariant } from "../invariant";
export const createSafeContextHook = <TContextValue>(
context: Context<TContextValue>,
displayName: string
) => {
return () => {
const contextValue = useContext(context);
invariant(
contextValue,
`${displayName} must be used within a ${displayName}Provider.`
);
return contextValue;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment