Last active
May 5, 2022 08:29
-
-
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.
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 { 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