I am getting this error when using the useState
hook. I have this in it's basic form, looking at the react docs for a reference, but am still getting this error. I'm ready for the face palm moment...
export function Header() { const [count, setCount] = useState(0) return <span>header</span> }
Solution 9: Invalid hook call. Hooks can only be called inside of the body of a function component. When you face this issue you just need to reinstall this “npm install react-bootstrap@next [email protected]” then your error will be resolve.
Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders.
you can create hook functions apart, but they are meant to be consumed by components.
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. (We don't recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you'd like.)
New version of react-hot-loader
is out now, link. Hooks is now working out of the box. Thank to the author, theKashey.
Check out this boilerplate https://github.com/ReeganExE/react-hooks-boilerplate
First, make sure you installed react@next
and react-dom@next
.
Then check for you are using react-hot-loader
or not.
In my case, disable hot loader & HMR could get it work.
See https://github.com/gaearon/react-hot-loader/issues/1088.
Quoted:
Yes. RHL is 100% not compatible with hooks. There is just a few reasons behind it:
SFC are being converted to Class components. There is reason - to be able to forceUpdate on HMR, as long there is no "update" method on SFC. I am looking for other way of forcing the update (like this. So RHL is killing SFC.
"hotReplacementRender". RHL is trying to do React's job, and render the old and the new app, to merge them. So, obviously, that's broken now.
I am going to draft a PR, to mitigate both problems. It will work, but not today.
There is a more proper fix, which would work - cold API
You may disable RHL for any custom type.
import { cold } from 'react-hot-loader'; cold(MyComponent);
Search for "useState/useEffect"
inside component source code, and "cold" it.
As per updated from react-hot-loader maintainer, you could try react-hot-loader@next
and set the config as bellow:
import { setConfig } from 'react-hot-loader'; setConfig({ // set this flag to support SFC if patch is not landed pureSFC: true });
Thank to @loganfromlogan for the update.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With