Loading State Visuals: how to make waiting more fun...
DwightColbyJack
Posted on June 13, 2021
No one likes waiting. It's the down time we could be using to eat snacks, text friends and try to rearrange our to-do lists for maximum laziness. Waiting for a page load, especially, is some of the most audacious down time because computers are supposed to be fast. However, given the asynchronous state of our functions, the business of our network or even just the strength of our internet signal, we will need to wait so we might as well make it look cool. Enter nProgress, a styling package that helps us add styles to our loading state so we can have a visual representation of our downtime with cool animations and color schemes.
To use nprogress, all we have to do is import it
import 'NProgress from 'nprogress'
and the associated styling that comes with the package.
import 'nprogress/nprogress.css'
NProgress comes with it's own methods that let us start the progress bar
NProgress.start()
We can also set it to a certain amount or increment
NProgress.set()
NProgress.inc()
and finally we can stop the animation with
NProgress.done()
In my Advanced React and GraphQL tutorial we go over page load, and how to use NProgress to give us some visual effects to display our loading state. Utilizing the NextJS Router component, we are able to listen to Router based events, specifically
Router.events.on(
routeChangeStart)
This gave us something to listen for before starting the NProgress effects
The final implementation looks something like this
Router.events.on('routeChangeStart', () => NProgress.start()).
Router.events.on('routeChangeComplete', () => NProgress.done())
A caveat here if you're using styled components is that the server and the client might be rendering different identified components (meaning styled components has an id for it, and the server has it's own id). Should this be the case, you'll recieve a scolding from the console and we have some light editing to do. Make sure you use thegetInitialProps
hook. The implementation is pretty heavy, and honestly this is a great example of reading your Docs because it looks weird, but it handles this problem quite nicely:
static getInitialProps({ renderPage }) {
`
const sheet = new ServerStyleSheet();
const page = renderPage((App => (props) =>
sheet.collectStyles( <App {...props} />
);
const styleTags = sheet.getStyleElement();
return {...page, styleTags };
}
So, that was alot, but bear in mind we are asking our App component to render with spread props a-la the "spread" operator, meaning we have essentially collected all the styles from the page as well as any initial styles from the server. Now the id's on the server and client side styled components can "work together".
Posted on June 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024