1

In a new create-react-app, hot reloading seems to be taking effect only for css files. In the simple example below, clicking on the first hello increments the timer to 1. Then, when I change e.g. the second "Hello" text to "Goodbye", the page reloads and the timer is set to 0 again.

Am I misunderstanding hot-reloading perhaps? I thought that it's purpose is to stop the re-render from happening.

import React from 'react';
import './App.css'

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      timer: 0,
    };
    this.timerInc = this.timerInc.bind(this);
  }

  timerInc() {
    this.setState({
      timer: 1,
    })
  }

  render () {
    return (
    <div className="App">
      <h1 onClick={this.timerInc}>Hello</h1>
      <h1>{this.state.timer}</h1>
      <h1>Hello</h1>
    </div>
  )};
}

export default App;
Bishonen_PL
  • 1,400
  • 4
  • 18
  • 31
  • If you are changing the text in your component's `render` function, it's expected that the component will re-render, because you've just changed it. It has to re-mount because the code changed and it can't know the previous state since that belongs to a different component instance. – Marko Gresak Apr 12 '20 at 10:46
  • If you want to persist the state, you would have to refactor the structure to have a "container" component for the state: https://stackoverflow.com/a/43414525/1276128 – Marko Gresak Apr 12 '20 at 10:48
  • `react-redux` also attempts to persist the state between hot reloads, but as with everything, it's not 100% reliable. It could happen that it refreshes incorrectly, showing you an invalid state. While the hot reload is cool and it speeds up the development-check cycle, I would not go overboard with making it work at all costs. I believe a refresh is good enough as a fallback. If it's too slow and you can afford to optimize, spend time on optimizing the initial load for all users, not just the hot reload fanciness for development builds :) – Marko Gresak Apr 12 '20 at 10:56

0 Answers0