Create default values for React contexts that throw a clear error when they are accessed outside their provider.
npm install react-context-default-errorpnpm add react-context-default-errorbun add react-context-default-errorUse defaultError as the default value for a context when there is no meaningful fallback value.
import { createContext, useContext } from "react";
import { defaultError } from "react-context-default-error";
interface AuthContextValue {
userId: string;
signOut: () => void;
}
const AuthContext = createContext(defaultError<AuthContextValue>("AuthContext"));
export function useAuth() {
return useContext(AuthContext);
}If a component calls useAuth() outside <AuthContextProvider>, any attempt to read the returned context value throws:
AuthContext can only be accessed within a <AuthContextProvider>
Pass errorMessage when you want complete control over the thrown message.
const AuthContext = createContext(
defaultError<AuthContextValue>("AuthContext", {
errorMessage: "useAuth must be used inside AuthContextProvider.",
}),
);Returns a proxy typed as T. The proxy throws a pre-created Error whenever it is read, called, mutated, enumerated, or otherwise inspected.
contextName: string- the context name used in the default error message.options?: { errorMessage?: string }- optional custom error message.
${contextName} can only be accessed within a <${contextName}Provider>
React's createContext requires a default value. For contexts that must always be provided, a fake default can hide bugs or fail later with unclear errors. defaultError keeps the context type strict while failing immediately with an actionable message.
MIT