Skip to content

Instantly share code, notes, and snippets.

@dkacper
Last active May 5, 2022 08:29
Show Gist options
  • Save dkacper/b7638f076a22c9bcac62c41df54eb9f8 to your computer and use it in GitHub Desktop.
Save dkacper/b7638f076a22c9bcac62c41df54eb9f8 to your computer and use it in GitHub Desktop.
React useContext hook but with a safe type check that makes sure context is not undefined.
import { Context, useContext } from 'react';
export const useContextSafe = <TContext>(
context: Context<TContext>
): NonNullable<TContext> => {
const ctxValue = useContext(context);
if (!ctxValue) {
throw new Error(
`Cannot read ${context.displayName} context. You may have forgot to wrap it with the Provider`
);
}
return ctxValue as NonNullable<TContext>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment