Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the home screen. In React, I could easily achieve this using window.onload(loaded()) but in NextJS, how can I accomplish the same result without relying on the window object? My main goal is to ensure that the loaded() function runs only once during the initial app load.

Below is my code, any help would be appreciated:

import Head from 'next/head';
import { useState, useEffect } from 'react';

import {
  Navbar,
  Hero,
  Showcase,
  Skills,
  Services,
  Footer,
  ProjectCard,
  Loader,
} from '../components';

const Loadera = () => {
  return (
    <div className="bg-blue-500 h-[100vh] w-[100vw] flex items-center justify-center text-center flex-col">
      <h1 className="text-white mb-4 text-5xl ">Welcome!</h1>
      <h1 className="text-white mb-4 text-2xl ">One Moment Please...</h1>
      <Loader size="lg" />
    </div>
  );
};

export default function Home() {
  const [loading, setLoading] = useState(true);

  const loaded = () => {
    setTimeout(() => {
      setLoading(false);
    }, 1500);
  };
  useEffect(() => {
    loaded();
  }, []);

  return (
    <div>
      <Head>
        <title>Seth&apos;s Place</title>

        <meta
          name="viewport"
          content="width=device-width, initial-scale=1"
        ></meta>
      </Head>
      {loading ? (
        <Loadera />
      ) : (
        <div className="min-h-screen">
          <div className="image-bg">
            <Navbar />
            <Hero />
          </div>
          <ProjectCard />
          <Skills />
          <Services />
          <Footer />
        </div>
      )}
    </div>
  );
}

Answer №1

To optimize the loading screen so it only displays once, create a flag that checks if the screen has already loaded. Once the initial load is complete, set the flag to true to prevent unnecessary reloads.

import Head from 'next/head';
import { useState, useEffect } from 'react';

import {
  Navbar,
  Hero,
  Showcase,
  Skills,
  Services,
  Footer,
  ProjectCard,
  Loader,
} from '../components';

const Loadera = () => {
  return (
    <div className="bg-blue-500 h-[100vh] w-[100vw] flex items-center justify-center text-center flex-col">
      <h1 className="text-white mb-4 text-5xl ">Welcome!</h1>
      <h1 className="text-white mb-4 text-2xl ">One Moment Please...</h1>
      <Loader size="lg" />
    </div>
  );
};

export default function Home() {
  const [loading, setLoading] = useState({
    load: true,
    loadedOnce: false,
 });

  const loaded = () => {
    setTimeout(() => {
      setLoading({
        load: false,
        loadedOnce: true,
      });
    }, 1500);
  };
  useEffect(() => {
    loaded();
  }, []);

  return (
    <div>
      <Head>
        <title>Seth&apos;s Place</title>

        <meta
          name="viewport"
          content="width=device-width, initial-scale=1"
        ></meta>
      </Head>
      {loading.load && !loading.loadedOnce ? (
        <Loadera />
      ) : (
        <div className="min-h-screen">
            ...
        </div>
      )}
    </div>
  );
}

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

Steps for Implementing a Delay on Bootstrap Dropdown Hover

Is there a way to create a delay for the bootstrap dropdown feature while ensuring that it still appears on hover? If you want to test this, click here: http://www.bootply.com/YcVBzvXqrR This is the HTML code I'm using: <div class="container"&g ...

How can you tap into local storage in CSS while utilizing a chrome extension?

Can I access local storage from a Chrome extension's options file using CSS? Is it possible to use JavaScript to define a variable that can be utilized in CSS, or is local storage only accessible through JavaScript? If local storage is restricted to J ...

Which specific graphing library does GitHub utilize for its Graphs section?

Which graphing library is utilized by GitHub on its Graphs tab? The graphs displayed at https://github.com/USER/REPOSITORY/graphs/commit-activity are visually appealing, detailed, and adaptable. If they are leveraging an open source javascript library fo ...

Filtering text for highlighting in Vue.js is a breeze

Struggling to create a text highlight filter using vuejs. The task involves iterating through an array of words, highlighting any matches with a span and class. However, I'm facing difficulty in getting the data to return with proper HTML formatting i ...

Tips for submitting a checkbox value even when it is disabled

I attempted to make the checkbox readonly, but users were still able to check/uncheck the field. Next, I tried disabling the checkbox which successfully prevented user interaction. However, when attempting to submit the form, the disabled checkbox value ...

NextJS is not displaying data fetched from getStaticProps on the page, although it is present in the props

I'm facing an issue with NextJS when trying to display text fetched from my API call. Essentially, I send an external HTTP request to retrieve some sample data. The data is returned as props for the component using the getStaticProps method. Within my ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

NextJS is crawling at a snail's pace

Currently, I am developing a website using Next.js and I am encountering some frustration with the Link component and router functionality. Whenever I click on a link, there is an unpleasant delay before the page loads and even when I try to use the browse ...

Modifying the color of a specific div using jQuery

I am attempting to develop a function that changes the background color of a div when a user clicks on it and then clicks on a button. The value needs to be saved as a variable, but I'm having trouble getting it to work because it keeps saying that th ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

Failed to dynamically load MUI icon in Next.js

Attempting to utilize dynamic loading of icons: "use client" import dynamic from 'next/dynamic'; const DynamicIcon = ({ iconName }) => { const IconComponent = dynamic(() => import(`@mui/icons-material/${iconName}`).then((mo ...

What is the best way to use jQuery AJAX to make changes to an HTML element that will be permanent even after the page is refreshed?

Starting out with codeigniter, I am working on building an ecommerce website. Every time a user clicks the "Add to cart" button in my view, I utilize jquery ajax to send a request to a controller function. This function then returns two variables: count ( ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

Utilizing jQuery and CSS to make an entire div clickable, and activate an 'a' tag hover state upon hovering

Looking to create a clickable link for the .wrapper div that directs users to the location of a.icon. Want the .wrapper div to activate the a.icon:hover state when hovered over, not just when hovering over the icon itself. Any assistance would be highly a ...

Which internal API allows for navigating to the daygridmonth, timegridweek, and timegridday views using a custom button?

I am looking to have the dayGridMonth displayed when I click on a custom button within FullCalendar. The functionality I want is for the dayGridMonthFunc to access the internal API daygridmonth and display the screen as a month. <div> & ...

Failure to Trigger jQuery.ajax Success Callback Function

My JavaScript Ajax call using jQuery.ajax is experiencing an issue where the success callback function does not execute. $.ajax({ url: target, contentType: 'application/json; charset=utf-8', type: 'POST', ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

Tips for effectively combining the map and find functions in Typescript

I am attempting to generate an array of strings with a length greater than zero. let sampleArray2:string[] = ["hello","world","angular","typescript"]; let subArray:string[] = sampleArray2 .map(() => sampleArray2 .find(val => val.length & ...

Issue encountered while deploying on vercel: TypeError - Trying to access properties of undefined (specifically 'and')

Encountered this issue during deployment on Vercel. Npm run build did not show any errors. Configuration : "node": "18", "next": "^14.0.0", "next-transpile-modules": "^9.1.0", An error occurred d ...

Browserify does not provide access to the require function in the browser environment

I am currently in the process of developing a web application using node.js along with express. My goal is to leverage Browserify in order to expose my local modules to the browser. Here is the structure of my application: ├── app.js ├── lib ...