skip to Main Content

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:

enter image description here

enter image description here

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


  1. useEffect used for functional componet. for class component you need to use
    componentDidUpdate and componentDidMount

    In your case :

    import React  from "react";
    
    
    class CustomerOnboarding extends React.Component {
      componentDidMount() { // this is for class component
        document.title = `Greetings to aaaa`;
      }
      render() {
        return (
          <div></div>
        );
      }
    }
    
    export default CustomerOnboarding;
    

    for using of useEffect you can change your Component to functional component :

    import React, { useEffect } from "react";
    
    
    function CustomerOnboarding() {
      useEffect(()=>{
        document.title = `Greetings to aaaa`;
      },[]);
      return (
        <div></div>
      );
    }
    
    export default CustomerOnboarding;
    
    Login or Signup to reply.
  2. or you can convert your component to function like below

    import React, { useEffect } from "react";
    
    const CustomerOnboarding = () => {
      useEffect(() => {
        document.title = `Greetings to aaaa`;
      }, []);
    
      return <div></div>;
    };
    
    export default CustomerOnboarding;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search