[useContext] Throw error if 'useContext' is used outside function components
See original GitHub issueDo you want to request a feature or report a bug? Feature (need better errors)
What is the current behavior? Consider the following functional component
import React, { useContext } from "React"
const myFunctionComponent = props => <div>Hello useContext</div>
The immediate reaction for most of us (newbies to hooks) to refactor the above code to accomodate useContext
is as follows
import React, { useContext } from "React"
import MyContext from "./MyContext"
// React does not throw error
const { myContextValue } = useContext(MyContext)
const myFunctionComponent = props => <div>Hello useContext - {myContextValue}</div>
The way to actually refactor is to explictly convert the arrow function return expression into a function body and then accomodate useContext
inside along with a return statement, like this
import React, { useContext } from "React"
import MyContext from "./MyContext"
const myFunctionComponent = props => {
const { myContextValue } = useContext(MyContext)
return (<div>Hello useContext - {myContextValue}</div>)
}
Not only, react does not throw error, React app actually compiles, while the component in question fails to load with no information. This is very difficult to pin the reason to this specific issue.
What is the expected behavior?
React should ideally throw some kind of error, when useContext
is used outside of function components. This lack of error really bites us for people who are refactoring function components without a return statement.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React 16.8.x
with hooks support
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (2 by maintainers)
@gaearon Gotcha … The problem is with react-loadable which for some reason swallows the error thrown by React. A reproducible snippet here - https://codesandbox.io/embed/l9m2v4l2zz. I’m also using
react-loadable
in my local project and after lots of trial and error, pinned down thisreact-loadable
issue. You can see the ‘loading’ text without any errors, which should actually show the hooks error. The invalid hooks call is inhello.js
fileLet me know if this is enough info.
I think this is not an issue with
react
per se and can be closed.