Loading screen in Next.js

Is there a way to implement a loader page during transitions within the same web application using Next JS?

During development, the pages transition smoothly with the CSS applied correctly. However, when moving the application to production environment, there is a brief moment where the transition appears like this for 1 or 2 seconds: https://i.sstatic.net/bgVSD.png

After this short delay, the page renders as expected: https://i.sstatic.net/rBypo.png

I am unsure of how to address this issue and believe it could potentially be resolved through one of two solutions:

  1. Implementing a loader page between page transitions.
  2. Making adjustments to _app.js or _document.js, although I am not sure where to begin with this approach.

Answer №1

To address the rendering issue, it is necessary to import Link from next.js. If you wish to implement a loading screen, you can utilize hooks as shown below:

import {useState, useEffect} from 'react';
Router from 'next/router';

function MyComponent() {
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    Router.events.on('routeChangeStart', () => setLoading(true));
    Router.events.on('routeChangeComplete', () => setLoading(false));
    Router.events.on('routeChangeError', () => setLoading(false));
    
    return () => {
      Router.events.off('routeChangeStart', () => setLoading(true));
      Router.events.off('routeChangeComplete', () => setLoading(false));
      Router.events.off('routeChangeError', () => setLoading(false));
    };
  }, [Router.events]);
    
  return (
    <>
    {
      (loading)
      ?
      <p>Loading...</p>
      :
      <p>Home</p>
      
    } 
    </>
  );
}

Answer №2

When tackling this issue, there are two different perspectives to consider.

  1. You can apply animations to individual page entries/exits (fade out/fade in), which essentially means that components can implement a CSS-based transition as the routes are loaded and the transition is applied to the parent container at the page level.
  2. Alternatively, you can animate individual elements as they are removed from view.

If you prefer to customize your own solution, you can explore

Both of these methods expand upon the concepts mentioned above.

  1. If you are comfortable with using Framer - check out
  2. For next page transitions that focus more on the react transition group, visit https://github.com/vercel/next.js/tree/canary/examples/with-next-page-transitions

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

JavaScript: The variable `scopes` is declared

I'm completely new to JavaScript. Can anyone help me understand why this code isn't working, and what changes I need to make to fix it? function getResults(keywords) { foo.foo = function() { var bar = foo.getSomeText; // ...

Adjusting the text and background hues using JavaScript results in an immediate reversal

Attempting to dynamically change the text color and background color based on user input in the textbox. While it initially works, the color changes only flash for a brief moment before reverting back. <!DOCTYPE html> <html> <head> ...

Developing User-Friendly Websites with Responsive Design

While I was working on my project, I realized that using only pixel values in tables and sidebars was a big mistake. This caused issues because if someone had a different screen resolution, my website would look distorted and unappealing. Could you please ...

ASP.NET CodeBehind Fails to Recognize Changes in TinyMCE Textarea

I have multiple <asp:TextBox TextMode="MultiLine"> elements on a webpage. Initially, I populate them using VB code behind and then convert them into TinyMCE editors with the help of the jQuery TinyMCE plugin. Each text box has an associated button fo ...

Custom date formatting with jQuery table sorting

I have been using a jQuery plugin called Tablesorter to sort a table. I am facing an issue with sorting dates in the yyyy MMM dd format, especially because my date inputs are in French. Here is an example of how the dates are formatted: 2014 janv. 05 20 ...

Issue with Vue.js: The input value text is not being updated

In my current setup, I am dealing with an input component that is linked to a variable called 'searchText' in the parent component. This variable stores the text value of the search input. The {{searchText}} in the template updates accurately bas ...

Parsing JSON data results in a string output

After realizing that my initial post was not clear enough, here are more details. Jade: meta(name='revObj', content=(JSON.stringify('#{rev[1]}'))) The resulting HTML from Jade: <meta name="revObj" content=""{ companyAddress: &apo ...

Vercel offers unique functionality specifically designed for Next.js

As part of my application migration process, I am transitioning to the nextjs framework. I am curious if all the features and functionalities offered by Next.js can be replicated on private Docker servers or other Jamstack platforms, or if there are limi ...

What is the best way to continuously loop the animation in my SVG scene?

After designing a SVG landscape with an animation triggered by clicking the sun, I encountered an issue where the animation only works once. Subsequent clicks do not result in any animation. Below is my current JavaScript code: const sun = document.getEle ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

Static files fail to load in FastAPI

Recently, I decided to switch my project from using node.js to python FastAPI. While everything was running smoothly with node, I encountered an issue with my static files not being found in FastAPI. Here is the code snippet that I am using: from fastapi i ...

Overlay text on top of image with fading transparency when hovering over it

Is there a way to make the transparent layer that appears when hovering over an image on a card only cover the image itself and not extend onto the footer of the card? Currently, the image on the card covers most of it, and I want the hover overlay to beh ...

When viewed on mobile devices, the image shrinks significantly

I'm experiencing an issue where the image shrinks significantly when viewed on a mobile device or when zooming in the browser. Can you help me understand why this is happening and suggest a solution? Here are the HTML and CSS code snippets: HTML < ...

Is it possible to retrieve information from the prefetch function and use it as an argument for another prefetch function in React-query?

In simple terms, I have a situation where I need to retrieve some data first and then use that data to fetch additional information. The catch is that I need an ID value from the initial data in order to do so. My entire page is statically generated (SSG ...

How is it possible for this variable to be altered without any modifications made to it in the current function?

This particular function receives two arrays as input: arrOne, which is an array comprising arrays of numbers, and arrTwo, which is an array containing numbers. My goal here is to generate every possible combination, followed by obtaining the unique combin ...

Is there a way to align the image block-grid from left to right?

Is there a way to change the alignment of images in the x-block-grid four-up class to be RTL on this page? () I have managed to make the h2 tag RTL using the following code: <h2 class="h-custom-headline h5 accent" dir="rtl"><span>Code</spa ...

Using discord.js within an HTML environment can add a whole new level of

I'm in the process of creating a dashboard for discord.js, however, I am facing difficulties using the discord.js library and connecting it to the client. Below is my JavaScript code (The project utilizes node.js with express for sending an HTML file ...

What is the best way to skip the additional step of "Sign In With Cognito" in next-auth and go straight to the sign-in form?

When working on my Next.js project and utilizing Cognito for sign-in through the next-auth library, I encounter a initial step where I have to click a button labeled "Sign in with Cognito" before being directed to the actual sign-in form. Is there a way to ...

Transferring information between a service and a controller

I'm struggling to pass data between a service and a controller in my AngularJS project. Even though I've followed the recommended steps, the code is not functioning as expected. Below is the controller snippet: function udpController($scope ...