Postulate is the best way to take and share notes for classes, research, and other learning.
In React apps, navigation between pages happens via a custom router rather than the browser loading a new page. This is great -- it's often a much nicer experience for both the user and developer. However, when transitioning between pages, the browser's loading indicators don't display like they would for a traditional page transition. Thus, your app can seem unresponsive rather than snappy, especially for Next.js apps with serverside requests before rendering the page.
A solution to this is to add a page loading bar to the top of your app, so that when you transition between pages a loading indicator will show and it won't seem like your app is just hanging.
With Next.js, it's stupidly easy to add this loading bar using Next's built-in router events and a package called nprogress
. Here's how to do it.
Run npm i nprogress
to install nprogress, then import it to pages/_app.tsx
with import NProgress from "nprogress";
.
Create an nprogress.css
somewhere in your project and paste in the contents of NProgress' stylesheet. Change around colors and other styling to your liking. Then, import the stylesheet to your _app.tsx
, i.e. import "../styles/nprogress.css";
.
Lastly, in _app.tsx
, import Router
from next/router
and then add three event handlers before your exported component:
import {AppProps} from "next/app"; import Router from "next/router"; import NProgress from "nprogress"; import "../styles/nprogress.css"; Router.events.on("routeChangeStart", (url) => { console.log(`Loading: ${url}`) NProgress.start() }); Router.events.on("routeChangeComplete", () => NProgress.done()); Router.events.on("routeChangeError", () => NProgress.done()); export default function App({Component, pageProps}: AppProps) { const router = useRouter(); return ( <Provider session={pageProps.session}> <div id="app-root"> <Component {...pageProps} /> </div> </Provider> ) }
For a full reproduction, see Vercel's official with-loading
example in the next.js repo.
Just like that, though, we're done! Our pages are now much nicer to navigate between with a beautiful loading bar at the top.
Founder and dev notes from building Postulate