What is the difference between NextJs Singleton Router instance vs useRouter()?

Viewed 64

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.

0 Answers
Related