question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

useRouter() throws "Invalid hook call" when extending React.Component

See original GitHub issue

Bug report

Describe the bug

When using useRouter() in a class that extends React.Component the following error is thrown:

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
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

To Reproduce

  1. Clone the Dynamic Routing Example
  2. Modify post/[id]/index.js to extend React.Component
import React from 'react';
import { useRouter } from 'next/router'
import Link from 'next/link'
import Header from '../../../components/header'

class Post extends React.Component {
  render() {
    const router = useRouter()
    const { id } = router.query

    return (
      <>
        <Header />
        <h1>Post: {id}</h1>
        <ul>
          <li>
            <Link href='/post/[id]/[comment]' as={`/post/${id}/first-comment`}>
              <a>First comment</a>
            </Link>
          </li>
          <li>
            <Link href='/post/[id]/[comment]' as={`/post/${id}/second-comment`}>
              <a>Second comment</a>
            </Link>
          </li>
        </ul>
      </>
    )
  }
}

export default Post;
  1. Navigate to the page.

Expected behavior

useRouter() to work as expected.

System information

  • OS: macOS 10.14.6
  • Version of Next.js: 9.0.3
  • Version of React: 16.8.6
  • Version of react-dom: 16.8.6

Additional context

Could possibly be related to #7626 withRouter() HOC can be used as workaround.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

9reactions
UnsolvedCyphercommented, Sep 16, 2019

To access the router inside getInitialProps, just have getInitialProps take in router as a parameter. To access it anywhere else, use this.props.router. And don’t forget to wrap the exported component with withRouter() 😃

import { withRouter } from 'next/router';

class SomePage extends Component {
  constructor(props) {
    super(props);
    this.state = { something: 0 };
  }

  static async getInitialProps(router) {
    const res = await fetch(`http://localhost:3000/some-api/${router.query.id}/`);
    const data = await res.json();
    console.log(`Data is: ${data}`);
    return {
      data: data,
    };
  }

  render() {
    return (<p>Here is the id that was passed: {this.props.router.query.id}</p>);
}

export default withRouter(SomePage);
7reactions
ZoomAllcommented, Aug 17, 2019

Hey, guys. Could you give an example of how to use withRouter in this case?

Read more comments on GitHub >

github_iconTop Results From Across the Web

NextJS useRouter error when used inside function body
You can call only useRouter() inside of Top of the React function component or custom hooks. Learn more about Rules of Hooks here ......
Read more >
Invalid Hook Call Warning - React
You are probably here because you got the following error message: Hooks can only be called inside the body of a function component....
Read more >
invalid hook call react router | The AI Search Engine You Control
When using useRouter() in a class that extends React.Component the following error is thrown: Invalid hook call. Hooks can only be called inside...
Read more >
NextJS useRouter error when used inside function body-Reactjs
Getting this error "Invalid hook call. Hooks can only be called inside of the body of a function component." inside a react functional...
Read more >
Invalid hook call. Hooks can only be called inside the body of ...
Having multiple versions of the react package in the same project. Trying to call a component as a function, e.g. App() instead of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found