node.jsnext.js

Trigger client-side reload in next.js


Scenario

The index page uses "getInitialProps" to load data. Then we create a dialog which can create a new data. After creating a new data, the current page should be reloaded.

Problem

We use Router.replace('/') to reload the page. But it triggers a server-side rendering.

Question

What we need is a client-side reload. The "getInitialProps" function should be called in the browser. So, how to do the client-side reload?


Solution

  • as of of NextJs 13 Being released the new router Object has the refresh() method, which allows you to refresh ( re-fetch ) the data client-side only without having to do a full page reload.

    it can be used like the following :

    import { useRouter } from "next/navigation";
    
    export default function Component(){
      const router = useRouter();
    
      //this will reload the page without doing SSR
      router.refresh();
    }
    
    

    Please keep in mind that this is feature of NextJs 13 Which is currently in beta.

    check the beta docs here

    credits to fireship for showing the feature
    https://www.youtube.com/watch?v=__mSgDEOyv8