Webpack/react hot reload reloading whole page?

8.1k Views Asked by At

This is probably asked all the time, but I've tried every approach under the sun and can't find a solution.

I've created a repo to make it easier to get help. You can clone it, run npm install and then npm start:dev to see a quick local server on http://localhost:8080.

It works, and when I change a file (say, src/components/Note/Note.css) the app does reload. However, I want to only reload the component, not the whole page. I'm not sure what I'm doing wrong. Any help will be appreciated!

2

There are 2 best solutions below

4
On BEST ANSWER

To debug issues like this, enable "Preserve log" in Chrome DevTools console settings to preserve console log across page refresh.

The error was:

Uncaught RangeError: Maximum call stack size exceeded

This was fixed once the following changes were made:

  1. Remove new webpack.HotModuleReplacementPlugin() from plugins (as webpack-dev-server is started with --hot)

  2. Also opt-out of babel transpiling ES6 modules by updating presets in .babelrc to ["react", ["env", { "modules": false }]].

"modules": false is to tell babel to not compile import/exports and let webpack handle it as described here and here (Check step 3.3.c).

0
On

For anyone using Next.js:

If you edit a file in pages/, the whole page will reload. Bummer, state is lost.

If you edit a file in components/, only the relevant module will re-load (i.e., hot reload as you expect).

My recommendation: keep the files in your pages/ folder simple. Iterate your design/details in a component file in the components/ folder.

For example:

// pages/welcome.jsx
import WelcomePage from "../components/welcomePage";

export default function Welcome() {
  return <WelcomePage />;
}

// components/welcomePage.jsx
import React from "react";
import Layout from "./layout";
import { useContext, useEffect, useState } from "react";
import PlayerContext from "../../context/playerContext";

export default function WelcomePage() {
  const { songTitle } = useContext(PlayerContext);
  return (
    <Layout>
      <div className="...">
        <div className="...">
          Welcome! Let's play {songTitle}.
        </div>
      </div>
    </Layout>
  );
}

Then you can go ahead and make small edits to components/welcomePage.jsx without losing state in your browser.