How to use "useRouter()" from next.js in a class component?

Shakirul Hasan picture Shakirul Hasan · Jul 14, 2019 · Viewed 10k times · Source

I was trying to get the queries from my url pattern like localhost:3000/post?loc=100 by using useRouter() from "next/router" and fetching some data using that id from my server. It worked when I used it in a Stateless Functional Component.

But the page showing "Invalid hook call" then. I tried calling getInitalProps() of a Stateless Functional Component, but it didn't work there either and showed the same error. Is there any rule to use this method?

I was developing a front-end using React Library and Next.js Framework.

constructor(props) {
  this.state = {
    loc: useRouter().query.loc,
    loaded: false
  };
}

Answer

Aprillion picture Aprillion · Jul 14, 2019

Hooks can be used only inside functional components, not inside classes. I would recommend to use withRouter HOC as per next.js documentation:

use the useRouter hook, or withRouter for class components.

Or see From Classes to Hooks if you want to switch to hooks.


In general, it's possible to create a wrapper functional component to pass custom hooks into class components via props (but not useful in this case):
const MyClassWithRouter = (props) => {
  const router = useRouter()
  return <MyClass {...props} router={router} />
}

class MyClass...
  constructor(props) {
    this.state = {
      loc: props.router.query.loc,
      loaded: false
    };
  }