2

I am using NextJS in my application. In that, for routing, we make use of the following:

import React from "react";
import {useRouter} from "next/router";

const IndexPage: React.FC = (props) => {
  const router = useRouter();

  useEffect(() => {
    router.replace('/home');
  }, []);

  return null;
};

This is what even the documentation recommends to follow. They make use of the useRouter hook to tap into the router instance and do stuff with it.

I have been using an alternative to the above approach. There is a singleton router instance that is the default export of the next/router file. It allows me to do routing stuff without tapping into the router instance using the hook.

import React from "react";
import Router from "next/router";

const IndexPage: React.FC = (props) => {

  useEffect(() => {
    Router.replace('/home');
  }, []);

  return null;
};

I like the second approach more. But, I see no documentation for this on the NextJs site. Not sure if this is the correct way to do routing. I want to know what is the difference between these 2 approaches and will second approach lead to any problems in the future.

vighnesh153
  • 4,354
  • 2
  • 13
  • 27
  • 1
    Testing would be easier if you can inject the router through a context – Bergi Jul 21 '21 at 08:22
  • 3
    Does this answer your question: [import Router from 'next/router' is it ok?](https://stackoverflow.com/questions/64325145/import-router-from-next-router-is-it-ok)? Also worth a read https://github.com/vercel/next.js/discussions/18522. – juliomalves Jul 21 '21 at 20:28
  • Yep. Thanks. This helps. – vighnesh153 Jul 22 '21 at 00:53

0 Answers0