Get in touch

Send an email to: lammers@gmail.com.
Or find me online at: Github, X

Custom hook instead of useContext

To avoid repeatedly having to check whether a context is defined in TypeScript, we can use a custom hook instead of useContext.

Given the following context:

type ContextType = {
  theme: 'light' | 'dark';
};

const ThemeContext = React.createContext<ContextType | null>(null);

When using useContext, the context could potentially be null:

function MyComponent() {
  const themeContext = useContext(ThemeContext);

  // Using optional chaining to prevent TypeScript from complaining:
  // 'themeContext' is possibly 'null'
  return <div>Current theme: {themeContext?.theme}</div>;
}

This custom hook can be used instead of useContext. It will make sure the context is only accessed within the ThemeContext.Provider, as it will throw an error when it's not. This also makes it unnecessary to check for null each time the context is used:

function useTheme() {
  const themeContext = useContext(ThemeContext);

  // Prevent the hook from being used outside of the ThemeContext.Provider
  if (!themeContext) {
    throw new Error('useTheme has to be used within <ThemeContext.Provider>');
  }

  return themeContext;
}

function MyComponent() {
  const themeContext = useTheme();

  // No need to check for null
  return <div>Current theme: {context.theme}</div>;
}