Community powered answers to your dev questions

Context without default value

posted: 2019 December 9th

category: typescript

Edit this post on GitHub.


A helper to create a context without the need for setting a default undefined value. This enables us to create our context and use it without checking it for undefined everywhere.

1function useCreateNoNullContext<T>(contextName: string) {
2 const context = React.createContext<T | undefined>(undefined);
4 function useNoNullContext() {
5 const noNullContext = React.useContext(context);
6 if (!noNullContext) {
7 throw new Error(`${contextName} must be used inside a provider with a value`);
8 }
9 return noNullContext;
10 }
11 return [useNoNullContext, context.Provider] as const;
12 }

Example usage:

1interface ContextValues {
2 isValue: boolean;
3 setValue: React.Dispatch<React.SetStateAction<boolean>>;
4 }
6 const [useContextValue, ContextValueProvider] = useCreateNoNullContext<ContextValues>('useContextValue');

useCreateNoNullContext returns a context hook and a provider. These can be named anything but the order is important as the first item is the context hook, while the second is the provider component. They can then be accessed like so:

1const {isValue, setValue} = useContextValue();

Author: Rich Haines