Skip to content
Discussion options

You must be logged in to vote

This is a very common and correct TypeScript error when dealing with React Context.
Your context definition:
const AuthContext = createContext<AuthContextType | null>(null);
correctly tells TypeScript that the value inside the context can be AuthContextType OR null.Your hook: return useContext(AuthContext)!; uses the non-null assertion operator (!), which silences the error but is generally discouraged as it hides potential runtime bugs.

Explicit Null Check and Custom Error for solve this issue..

Corrected useAuth Hook

export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);

  if (context === null) {
    throw new Error('useAuth must be used within an Au…

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by ttahasina
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug GitHub or a GitHub feature is not working as intended Projects Plan and track your project's progress using boards and tables
3 participants