How to Disable Live Reload in create-react-app

status
published
dsq_thread_id

How to disable live reload in create-react-app

Here you go, insert this code into your HTML file. Probably located at public/index.html.
<% if (process.env.REACT_APP_DISABLE_LIVE_RELOAD === "true") { %>
<!-- 
  Live Reload was causing issues for us. Disable it by starting the app with
  REACT_APP_DISABLE_LIVE_RELOAD=true
-->
<script>
  {
    var WS = window.WebSocket;
    function DevWebSocket(s) {
      if (s === "ws://localhost:3000/sockjs-node") {
        console.info("[DEV NOTICE] Live Reload Has Been Disabled");
        return {};
      } else {
        // Pass through other usage of sockets
        return new WS(s);
      }
    }
    window.WebSocket = DevWebSocket;
  }
</script>
<% } %>
Then on the command line just set that environment variable when you start the app:
REACT_APP_DISABLE_LIVE_RELOAD=true yarn start

A quick explanation

create-react-app uses web sockets to trigger a refresh in the browser. Since there is no option to disable this behavior we can take matters into our own hands. We do this by overwriting the global WebSocket constructor. Then if we detect that create-react-app is trying to set up live reload we just return an empty object. Voila.

Why?

Fair question. Usually live reload is a boon to development. However, I have a project where I'm using an app in development as a CMS. In a sense I'm running a "production" app in dev mode, which is admittedly odd.
The point though is that I'm using it as a CMS. That means I'm creating and editing content in the browser. If I notice something in the app that I want to change I might make a code change as well. A live reload could easily destroy any unsaved content I've created. Think of it like when your computer used to freeze in the middle of writing a long essay in Word. You might just lose all your progress, which is not great.
The broader point though is that philosophically I believe software should be configurable. This is doubly true for dev software. In the world of JS there seems to have been a trend away from configuration. I understand this since too much configuration (Webpack...) can turn developers away from otherwise interesting and useful projects. However, we can have the best of both worlds. Having sensible defaults that can be changed is the answer. Similar to the Ruby on Rails philosophy perhaps.
Have defaults, but let me configure them if my use case requires it.