React useEffect definition in class

Viewed 1297

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.

2 Answers

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]);
}
Related