I am learning react and trying to use useEffect
. But I am getting this error:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
To address #1 I checked the react and react-dom versions, they’re the same 18.2.0
.
To address #2 I don’t think I am (code coming soon). I’m not sure how to check for #3, I don’t think there is but then again not sure. Here is my code:
import React, { useEffect } from "react";
useEffect(() => {
document.title = `Greetings to aaaa`;
}, []);
class CustomerOnboarding extends React.Component {
render() {
return (
<div></div>
);
}
}
export default CustomerOnboarding;
Above code throws Invalid hook call
error. However when I put the useEffect
within the component class I get a slightly different error:
I don’t know if this is related, but I am using react with ruby on rails. I have other components working just fine, without hooks that is. Any ideas?
2
Answers
useEffect used for functional componet. for class component you need to use
componentDidUpdate and componentDidMount
In your case :
for using of useEffect you can change your Component to functional component :
or you can convert your component to function like below