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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With