Bug: useContext returns default instead of passed value
See original GitHub issueGiven the following code:
const TestContext = React.createContext('default');
export default () => (
<TestContext.Provider value='not default'>
<span>{React.useContext(TestContext)}</span>
</TestContext.Provider>
);
The resulting value in <span>
is “default”.
React version:
react@16.13.1
(@latest
)
react@0.0.0-d7382b6c4
(@next
)
Steps To Reproduce
A repo illustrating the issue is available.
The current behavior
React.useContext()
returns the default (the string “default”), despite the presence of a value
prop with another string.
The expected behavior
React.useContext()
should return the string “not default” or throw an error/warning.
Discussion
A slightly modified version of the above code
const TestContext = React.createContext('default');
const Inner = () => (
<span>{React.useContext(TestContext)}</span>
);
export default () => (
<TestContext.Provider value='not default'>
<Inner />
</TestContext.Provider>
);
Renders the string “not default”, as one might expect.
I’m guessing that this has to do with the rendering order of the components and is maybe unavoidable, but perhaps an error or warning should be thrown if a corresponding Context Provider isn’t available when useContext()
is called. This would force everyone to actually wrap all code in a Context Provider.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:7
- Comments:5 (1 by maintainers)
This is expected because
is the same as
In other words, components themselves are boundaries for context. Where you put a Hook call doesn’t play a difference.
it’s a confusing design. i think i just lost an hour there chasing this one. you can’t instantiate
useContext
in the component where it will be used? you have to instantiate in a separate component and then use that component in the original component?it still seems like a bug