Make it easier to debug when Context uses defaultValue accidentally due to no provider
See original GitHub issueI 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:
- Created 5 years ago
- Reactions:1
- Comments:6 (2 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
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.
A guy on my team wrote a simple little thing to help with this:
It returns the provider and a hook and throws an error if there’s no provider. It’s saved us a bunch of times.