Exporting components as the default from Next.js leads to a forced page refresh whenever there is a change

One issue I encountered involved having an index.tsx file containing all the shared UI components. When I exported the Footer and imported it into my shared Layout.tsx, which is utilized across all pages, the browser would refresh the page every time a change was made rather than performing a fast refresh.

This behavior occurred whenever I tried to default export any component and include it wherever needed.

Surprisingly, all child components functioned perfectly fine. The issues only arose when default exporting everything.

I am curious if there are any solutions, fixes, or reasons for this problem?

/components/ui/index.tsx:

export { default as Alert } from "./Alert"
export { default as Footer } from "./footer"
export { default as Logo } from "./logo"
export { default as MainNavigation } from "./main-navigation"
export { default as MaxWidthWrapper } from "./max-width-wrapper"
export { default as PageAnimate } from "./page-animate"
export { default as ThemeSwitch } from "./theme-switch"

Layout.tsx:

"use client"

import { MaxWidthWrapper, PageAnimate } from "@components/ui"

import { Footer, MainNavigation } from "@components/ui"

const Layout = ({ children }: { children: React.ReactNode }) => {
  return (
    <>
      <MainNavigation />
      <PageAnimate>
        <MaxWidthWrapper type="main">{children}</MaxWidthWrapper>
      </PageAnimate>
      <Footer />
    </>
  )
}

export default Layout

Footer.tsx:

"use client"

import { FaFacebook, FaTwitter, FaInstagram, FaYoutube } from "react-icons/fa"

import MaxWidthWrapper from "./max-width-wrapper"

import { SocialProps } from "types"

const Footer = ({ socialFields }: SocialProps) => {
  return (
    <MaxWidthWrapper
      container
      type="footer"
      className="flex flex-row items-center justify-between py-5 flex-nowrap"
    >
      <p className="text-xs">
        &copy; {new Date().getFullYear()} The Friendly Vegan24
      </p>

      <div className="flex justify-center space-x-3">
        <a
          target="_blank"
          rel="noreferrer"
          href="https://www.facebook.com"
          title="Instagram"
          className="flex items-center justify-center text-white rounded-full w-7 h-7 bg-sun sm:w-8 sm:h-8"
        >
          <FaFacebook className="w-4 h-4 text-midnight" />
        </a>

        <a
          target="_blank"
          rel="noreferrer"
          href="https://www.instagram.com"
          title="Facebook"
          className="flex items-center justify-center text-white rounded-full w-7 h-7 bg-sun sm:w-8 sm:h-8"
        >
          <FaInstagram className="w-4 h-4 text-midnight" />
        </a>

        <a
          target="_blank"
          rel="noreferrer"
          href="https://twitter.com"
          title="Twitter"
          className="flex items-center justify-center text-white rounded-full w-7 h-7 bg-sun sm:w-8 sm:h-8"
        >
          <FaTwitter className="w-4 h-4 text-midnight" />
        </a>

        <a
          target="_blank"
          rel="noreferrer"
          href="https://youtube.com"
          title="Twitter"
          className="flex items-center justify-center text-white rounded-full w-7 h-7 bg-sun sm:w-8 sm:h-8"
        >
          <FaYoutube className="w-4 h-4 text-midnight" />
        </a>
      </div>
    </MaxWidthWrapper>
  )
}

export default Footer

/pages/index.tsx (home)

import { NextSeo } from "next-seo"

import { ButtonProps } from "types"

import { Layout, SectionHeader } from "@components/sections"
import {
  Hero,
  InfoCard,
  Feature,
  Newsletter,
  BlogCard,
  Contact
} from "@components/blocks"
import { Grid, Section } from "@components/shared"

import HeroImage from "@images/hero.png"

const HomePage = () => {
  const HeroButtons: ButtonProps[] = [
    {
      id: 1,
      href: "/",
      text: "Get in touch!"
    },
    {
      id: 2,
      href: "/over-ons",
      text: "Over ons"
    }
  ]

  return (
    <Layout>
      <NextSeo
        title="Home"
        openGraph={{
          type: "website",
          url: "https://ffb-next-static.vercel.app",
          description:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec suscipit diam, ac scelerisque libero. Vestibulum sapien lorem, placerat quis orci id, tempor mattis felis.",
          images: [
            {
              url: "https://images.pexels.com/photos/1059823/pexels-photo-1059823.jpeg?auto=compress&cs=tinysrgb&w=1200&h=630&dpr=2",
              width: 1200,
              height: 630,
              alt: "We welcome you",
              type: "image/jpeg"
            }
          ]
        }}
      />

      <Hero
        funny
        buttons={HeroButtons}
        featuredImage={HeroImage.src}
        title="The Friendly Vegan"
        intro="Ruimte voor tekst om de bezoeker welkom te heten, of om te
            beschrijven wat je doet met je product of dienst."
      />

      <Section>
        <SectionHeader
          title="Onze werkzaamheden"
          text="Ruimte voor tekst om in te leiden welke stappen je hieronder gaat uitleggen. Bijvoorbeeld de waarden waar je bedrijf voor staat, of het proces wat je doorloopt."
        />

        <Grid>
          <InfoCard
            featuredImage="https://source.unsplash.com/1024x800/?food?1"
            title="Recepten"
            text="Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quas natus commodi repellendus."
          />

          <InfoCard
            featuredImage="https://source.unsplash.com/1024x800/?food?2"
            title="Catering"
            text="Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quas natus commodi repellendus."
          />

          <InfoCard
            featuredImage="https://source.unsplash.com/1024x800/?food?3"
            title="Workshops"
            text="Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quas natus commodi repellendus."
          />

          <InfoCard
            featuredImage="https://source.unsplash.com/1024x800/?food?4"
            title="Duurzaamheid"
            text="Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quas natus commodi repellendus."
          />
        </Grid>
      </Section>

      <Section>
        <Feature />
      </Section>

      <Section className="bg-sun sm:bg-transparent">
        <Newsletter />
      </Section>

      <Section>
        <SectionHeader
          buttonLink="/blog"
          buttonText="Naar alle artikelen"
          title="Blog"
          text="Ruimte voor tekst om in te leiden welke stappen je hieronder gaat uitleggen. Bijvoorbeeld de waarden waar je bedrijf voor staat, of het proces wat je doorloopt."
        />

        <Grid className="grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 pb-14">
          <BlogCard image="https://source.unsplash.com/1024x800/?food?8" />
          <BlogCard className="text-midnight bg-primary" />
          <BlogCard className="text-midnight bg-neutral" />
        </Grid>
      </Section>

      <Section className="bg-sun sm:bg-transparent">
        <Contact />
      </Section>
    </Layout>
  )
}

export default HomePage

Answer №1

Avoid using default exports whenever possible:

Footer.tsx:

export const FooterComponent = () => {
 //...
}

index.tsx:

export * from "./footer"
//...

Layout.tsx:

import { FooterComponent, MainNavigation } from "@components/ui"

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

Update the state within a forEach iteration

Is there a way to update state when clicking on buttons? I keep getting an error. Error: Uncaught TypeError: this.setState is not a function I understand that this.setState cannot be used here, but I'm unsure of where to bind it. class Popup extend ...

Embed a React component within another component

Recently, I've started learning React and I'm utilizing material-ui for my project. My goal is to create a customized autocomplete feature in React where selected data from the dropdown will appear as chips inside the text input field. I am curre ...

Upcoming: NextJS version 10 introduces enhanced i18n capabilities with the ability to customize folder names in

I am trying to create a multi-language website where I need to translate a specific folder differently for each language. The folder structure in question is as follows: pages/kennis/index.tsx I am having trouble figuring out how to translate the "kennis" ...

"Trouble with the accordion: How to make the first one open

Is there a way to make the first tab automatically expand when the page is refreshed? I want the General tab to be expanded by default like this: General (top header) (-) lorem ipsum (-) lorem ipsum doller amu site amu doller lorem ipsum (+) lorem i ...

File reading and processing must be completed before attempting to write to a new file. This is a promise-related stipulation

Feeling completely lost and stuck in a rut. Promises seemed straightforward until I actually tried to implement them. Sharing my basic code here without any promise attempts for simplicity's sake. After taking a few months hiatus from this, I returned ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

How can I incorporate popups in React using mapbox-gl?

Currently utilizing mapbox-gl within React, everything seems to be functioning properly except for the integration of mapbox-gl's Popups. I have the function let Popup, but I am uncertain about how to incorporate it. renderMap() { if (this.props. ...

Can a JavaScript class have a property that returns an array?

To those more experienced in node red development, this may be obvious, but I'll ask anyway. Within my node red flow, I have a function node containing a javascript class that only exposes static members. Here's an example: class MeasurementsLis ...

Confirm that the form is valid when a specific requirement is fulfilled

I am currently working on a credit card project that involves using a JavaScript function called validateCreditCard to validate credit cards and determine the type. The idea is to store the credit card type as the value of a hidden input field called cardT ...

Using AngularJs to have two ui-views on a single page

As a beginner in AngularJs, I encountered an issue with having two ui-views on the same page. When I click a button to show the view for goals, both the form for goals appear in ui-view 1 and ui-view 2 simultaneously. I have been working with states but I ...

In vuex, dynamic modules share common data and do not have unique data

Currently, I am facing an issue with an asynchronous API call that returns an array of objects. After receiving this data, I map it to dynamically registered modules in my store. The process looks something like this: dispatch // prior to this dispatch, ...

Is there a way to retrieve the text value of an input using just function components in React?

import Layout from "components/Layout" import { useState } from "react"; export async function getServerSideProps(context) { const res = await fetch(`${process.env.NEXT_API_URL}/kana-terms/all`) const data = await res.json() ...

Is there a way to set a default value for the map function?

Currently utilizing React.js with the following code snippet: myArray.map(variable=>({value: variable.value, label: variable.label})) It's working well for the most part, but occasionally encountering this issue: TypeError : myArray is null Any s ...

Error compiling: Cannot locate module '../../common/form' within 'src/components/time'

An attempt to import the file form.jsx into the file time.jsx resulted in an error: Error message: Module not found: Can't resolve '../../common/form' in 'src/components/time' //src //common //form.jsx //compon ...

Enhance a React component by including additional properties when passing it into another component through props

I have a parent element with a dynamically changing height that I need to pass down to its child elements. To get and set the height of the parent element, I am utilizing a ref. The challenge lies in passing this height value from the parent component to ...

"ReactJS error: Unable to upload file due to a 400

Every time I attempt to upload a file, I encounter this error: "Uncaught (in promise) Error: Request failed with status code 404". I'm puzzled as to why this is happening. Here's the section of my code that seems to be causing the issue. ...

Hiding the C3 tooltip after engaging with it

I'm currently expanding my knowledge on utilizing C3.js for creating charts, and one aspect I'm focusing on is enhancing the tooltip functionality. Typically, C3 tooltips only appear when you hover over data points as demonstrated in this example ...

Would you prefer to generate fresh HTML using JavaScript or dynamically load an existing HTML layout using AJAX?

I have a project where I need to generate a large amount of HTML that isn't currently on the page. Up until now, I've been using jQuery to construct the page piece by piece with JavaScript, adding divs and adjusting layouts as needed. Lately, I ...

Having trouble with jQuery focus not functioning properly?

I've been attempting to implement a focus function on a specific input in order to display a div with the class name .search_by_name when focused. However, I'm encountering issues and would appreciate it if someone could review my code to identif ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...