question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Make it easier to debug when Context uses defaultValue accidentally due to no provider

See original GitHub issue

I just spend several hours debugging app blaming everything except me ofc. I am using this useTheme Hook.

import React from 'react';
import ThemeContext from '../contexts/ThemeContext';

const useTheme = () => {
  const theme = React.useContext(ThemeContext);
  //if (theme == null)
  //  throw Error('useTheme: Please provide ThemeContext value.');
  return theme;
};

export default useTheme;

Some styles were light while other dark. Very strange. Then I found the bug in my code, ThemeContext.Provider was sometimes used after using useTheme. ThemeContext had an initial value different than provided.

While it’s probably fine that React allows us to use default context value without a parent provider, it can lead to hard to find bugs.

Therefore, I decided to never provide default context value and throw an exception in useFooContext hook to warn about it.

Because of DX, React should reconsider default / initial context values. In my humble opinion.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
gaearoncommented, Jan 18, 2019

I think what you’re saying is “React should make it easier to trace where the context value is coming from”. Like a stack or something. That would clue you in earlier.

2reactions
sunny-mittalcommented, Jan 15, 2020

A guy on my team wrote a simple little thing to help with this:

import React, { useContext } from "react";

export const createRequiredContext = <TContext extends any>(name: string) => {
  const Context = React.createContext<TContext>(undefined as any);
  const providerName = `${name}Provider`;
  const hookName = `use${name}`;

  Context.displayName = providerName;

  const hook = () => {
    // This is a factory function for a custom hook; it will eventually be
    // run within a function component.
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const context = useContext(Context);
    if (!context) {
      throw new Error(
        `${name} context not found. Please import ${providerName} and add it to a component above ${hookName}().`,
      );
    }
    return context;
  };
  return [Context.Provider, hook] as const;
};

It returns the provider and a hook and throws an error if there’s no provider. It’s saved us a bunch of times.

Read more comments on GitHub >

github_iconTop Results From Across the Web

React Context defaultValue returns undefined when no ...
If there is no Provider for this context above, the value argument will be equal to the defaultValue that was passed to createContext()....
Read more >
Typing React Context to avoid an undefined default value
In this function we create a context with a generic type and undefined as the default value, we then create another function to...
Read more >
October 2022 - Visual Studio Code
Learn what is new in the Visual Studio Code October 2022 Release (1.73)
Read more >
Changes — Flask Documentation (2.2.x)
The app and request contexts are managed using Python context vars ... Add --app and --debug options to the flask CLI, instead of...
Read more >
Network Debug and Troubleshooting Guide
If you are not using provider: nor top-level arguments ensure your inventory file is correct. Error: “Authentication failed” . Platforms: Any. Occurs...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found