2

I am trying to set useEffect hook (for listening to route changes) in my class that is defined like -

export default class AppManger extends Component{
    //constructor
    //componentWillMount
    //reneder
    //...
}

The rest of my hooks are defined and working as expected but when I try to define useEffect-

useEffect(() => {
        const { pathname } = location;
        console.log('New path:', pathname);
    }, [location.pathname]);

I get - ./src/components/AppManger.js

  Line 30:  Parsing error: Unexpected token

  28 |         }
  29 |     }
> 30 |     useEffect(() => {
     |               ^
  31 |         const { pathname } = location;
  32 |         console.log('New path:', pathname);
  33 |     }, [location.pathname]);

Is it the right way to define arrow function in React component?

Thank you.

Itsik Mauyhas
  • 3,163
  • 7
  • 48
  • 93

2 Answers2

0

No, my friend, you can not use hooks inside class components, To use you have to convert class component to functional component. Like this :

import React from "react";

export default AppManger = () => {
    useEffect(() => {
        const { pathname } = location;
        console.log('New path:', pathname);
    }, [location.pathname]);
}
0

useEffect and all other hooks can be used only in functional components. In your class component you should use lifecycle methods. Here is more info: 1) https://reactjs.org/docs/state-and-lifecycle.html - lifecycle methods 2) https://reactjs.org/docs/hooks-intro.html - hooks

Germs
  • 69
  • 6