Webpack/react hot reload reloading whole page?
Asked Answered
M

2

6

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!

Marcelina answered 13/12, 2017 at 22:1 Comment(0)
D
10

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).

Dealing answered 14/12, 2017 at 10:7 Comment(4)
Ohhhhhhhhhhhhhhhh THANK YOU!!Marcelina
Quick question: why do I need to opt-out of babel transpiling ES6 modules?Marcelina
Thanks for asking. I have updated the answer. Hope that helps.Dealing
How to solve this in 2020? I can't find these options in create-react-app project.Dilemma
A
0

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.

Aeroneurosis answered 3/2, 2021 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.