CodeBlanks Logo Icon CodeBlanks

Default value and error

Learn to write a hook that throws when used outside the provider.

Default value and error

Setting null as the default context value and using it without a check is a common bug. const user = useContext(UserContext); user.name crashes when there's no Provider.

The fix: give a default value object that throws an error. createContext({ '{ getName: () => { throw new Error("UserContext missing"); } }' }). So a meaningful error appears without a Provider.

A cleaner method: write a custom useUserContext hook. Call useContext(UserContext) inside; throw if null. This saves consumers from checking every time.

Custom useXContext hook

Writing a useXContext hook for each context is a good habit. Inside the hook: const ctx = useContext(XContext); if (ctx === null) throw new Error("Use inside XContext Provider"); return ctx;.

This gains three things: type safety (even stronger with TypeScript), consistent error messages, and central validation. Consumers call useUserContext() and skip the null check.

If you later want to add debug logs to the context, you only update this hook. All consumers benefit automatically. This approach saves lives in big projects.

Practice useUserContext guard

Complete the skeleton. Write a useUserContext hook. Call const ctx = useContext(UserContext);. If ctx === null, throw new Error("Use inside UserContext Provider");. Return ctx. Export the hook.

Starter code

App.jsx
import { useContext } from "react";

// Write the useUserContext hook here

Sample solution

App.jsx
import { useContext } from "react";

function useUserContext() {
  const ctx = useContext(UserContext);
  if (ctx === null) throw new Error("Use inside UserContext Provider");
  return ctx;
}

export default useUserContext;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a null default context cause?

  • Less code
  • Faster runtime
  • useEffect skipped
  • Crash when no Provider Correct answer

Explanation: null default crashes without a Provider.

2 Guard hook

Question
A guard hook throws when ____ is seen.
Answer
A guard hook throws when null is seen.

Explanation: Throws when null is seen.

3 Match the guard pattern

Term Meaning
useContext Read
null Error condition
throw Throw error
useXContext Hook

All lessons in Intermediate