Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useEffect dependencies when using NextJS router

I have a NextJS project, using the NextJS router to route the user to a page based on a certain state variable.

I looked up how to do what I want using the NextJS router documents which has this example:

const useUser = () => ({ user: null, loading: false })

export default function Page() {
  const { user, loading } = useUser()
  const router = useRouter()

  useEffect(() => {
    if (!(user || loading)) {
      router.push('/login')
    }
  }, [user, loading])

  return <p>Redirecting...</p>
}

When I stick that example into my code, ESLint isn't happy about me not including the router as a dependency - showing the following message:

React Hook useEffect has a missing dependency: 'router'. Either include it or remove the dependency array.eslintreact-hooks/exhaustive-deps

The message makes sense - we're using the useRouter hook in the effect but not adding it to the dependency array for the effect.

However, adding it to the dependency array naturally leads to an infinite re-render loop (as I'm using dynamic routing, so the same effect gets called over and over since router is changing).

Should I be ignoring the warning from ESLint, or should I be doing something different all together?

Edit: it's worth noting I'm using NextJS ESlint config

like image 961
adrian Avatar asked Mar 04 '26 03:03

adrian


1 Answers

Instead of using useRouter, use Router.

import Router from "next/router";

export default function Page() {
  const { user, loading } = useUser()

  useEffect(() => {
    if (!(user || loading)) {
      Router.push("/login");      
    }
  }, [user, loading])

  return <p>Redirecting...</p>
}

This is how I solved this issue in my code.

like image 189
kkSkr Avatar answered Mar 06 '26 18:03

kkSkr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!