Search code examples
reactjsnext.jsnext-router

Should I await a Router.push in NextJS


I am using NextJS and import Router from 'next/router'; The method that I use to navigate between pages is Router.push('/some-page'); This method is async, yet, it works without me adding an await Router.push('/some-page'); Am I using it correctly? I do not really want to execute any code that is below this point as I am really just redirecting the user. I cannot find anything useful in the official documentation.


Solution

  • The Router.push method returns a promise, which means it is an asynchronous operation. However, you don't necessarily need to use await with Router.push if you don't have any code that should wait for the navigation

    By not awaiting the promise, you are essentially not waiting for the navigation to finish before moving on to the next line of code. This still can be useful in scenarios where you want to trigger a navigation while also continuing to execute subsequent code without waiting for the navigation to complete.

    Again if in your case it's the last line of code where you're calling the push method, then it really doesn't matter if you await or not the returned promise

    If you have code that should only execute after the navigation is complete, such as updating state or fetching data on the new page, then you would need to use await or handle the navigation completion in a different way.

    So when should you wait? If you have code that should only execute after the navigation is complete, such as updating state or fetching data on the new page