Skip to content
Next.Js기술 정리

Next.js useRouter: push or replace

1 min readTech notesMoved from my Tistory blogRead the Korean original

js
import { useRouter } from "next/router";
import { useEffect, useState } from "react";

export default function useUser() {
  const [user, setUser] = useState();
  const router = useRouter();
  useEffect(() => {
    fetch(`/api/users/me`).then((response) =>
      response.json().then((data) => {
        if (!data.ok) {
          return router.replace("/enter");
        }
        setUser(data.profile);
      })
    );
  }, [router]);

  return user;
}

First, I learned something useful while building a hook that fetches and manages the user's information through useEffect(), so I'm writing it down.

With useRouter(), the push method leaves an entry in the browser history.

The replace method, on the other hand, doesn't leave a history entry.

I think this will be useful later if I write logic that redirects when someone accesses Home or a page that requires login.

  • #Next.js
  • #Push
  • #Replace
  • #Frontend Developer Sungjun Um

More in Tech notes