Next.js: next/router - push function changes between renders when called

Created on 22 Oct 2020  路  2Comments  路  Source: vercel/next.js

Bug report

Depending on the push function of useRouter causes an infinite loop when the push function is called from inside a useEffect

To Reproduce

  1. Set up a catch-all optional dynamic route [[...slug]].js
  2. Render the following component from this page
    Example component
const BugExample = () => {
    useEffect(() => {
        push('/[[...slug]]', '/123/test', { shallow: true })
        console.log('called');
     },[push])

    return null
}

You will see an infinite loop of called in the console

Expected behavior

Push should be a non-changing reference, so that the react diff algoirithm knows not to call side effects again uneccesarily

System information

  • OS: macOs
  • Browser: Chrome
  • Version of Next.js: 9.5
  • Version of Node.js: 13.2.0

Most helpful comment

Hi @jamesmosier - I would be of the opinion that the various router methods _should_ be using useCallback

The React hooks lint rule will complain if you do not include all dependencies in the array - we would prefer to not have to disable this lint rule.

All 2 comments

Hi @dan-cooke. I don't believe the various router.* methods use useCallback, therefore between renders push !== push.

Based on a few of the examples from the docs, router or push are not added as dependencies in the dependency array of useEffect.

It seems like a good workaround would be to exclude push from the dependency array.

Hi @jamesmosier - I would be of the opinion that the various router methods _should_ be using useCallback

The React hooks lint rule will complain if you do not include all dependencies in the array - we would prefer to not have to disable this lint rule.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

timneutkens picture timneutkens  路  250Comments

Timer picture Timer  路  87Comments

poyiding picture poyiding  路  73Comments

Knaackee picture Knaackee  路  122Comments

tomaswitek picture tomaswitek  路  73Comments