vercel / next.js

The React Framework
https://nextjs.org
MIT License
124.66k stars 26.61k forks source link

Chronic issue with router and exhaustive-deps eslint rule #40791

Open 11koukou opened 1 year ago

11koukou commented 1 year ago

Verify canary release

Provide environment information

Operating System: Platform: win32 Arch: x64 Version: Windows 10 Enterprise LTSC 2021 Binaries: Node: 16.5.0 npm: N/A Yarn: N/A pnpm: N/A Relevant packages: next: 12.3.2-canary.3 eslint-config-next: 12.2.2 react: 17.0.2 react-dom: 17.0.2

What browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

Describe the Bug

Using router=useRouter() instance inside useEffect triggers ESLint exhaustive-deps rule if not added as a dependency. However trying to fix it and adding router as a dependency leads to unneeded re-renders and potentially infinite loops. There's been an old discussion https://github.com/vercel/next.js/issues/18127 for this, however with not a clean solution.

Therefore the example https://nextjs.org/docs/api-reference/next/router#usage-6 in documentation needs URGENT update and needs an official workaround since copy pasting it triggers ESLint exhaustive-deps complaining!

Expected Behavior

useRouter hook should not cause re-renders.

Link to reproduction

https://nextjs.org/docs/api-reference/next/router#usage-6

To Reproduce

https://nextjs.org/docs/api-reference/next/router#usage-6

11koukou commented 1 year ago

The same for https://nextjs.org/docs/api-reference/next/router#usage-2

11koukou commented 1 year ago

Ok this is partially solved since properly unsubscribing from the router.events in useEffect's "return" prevents unnecessary re-renders but the example needs to be updated anyway with the ESLint rule