user11584620
user11584620

Reputation:

Why does localhost server start when running React?

create-react-app seems to start localhost server at npm start.

(npx comes with npm 5.2+ and higher, see instructions for older npm versions)

Then open http://localhost:3000/ to see your app.

When you’re ready to deploy to production, create a minified bundle with npm run build.

https://facebook.github.io/create-react-app/docs/getting-started

Why do I need to bring up a server just to run JavaScript?

What are the differences, advantages, and disadvantages of opening the build result file directly in the browser?

Also, is this true for other frameworks regardless of create-react-app?

I read React's repository etc on this issue, but there was no topic on this issue.

Upvotes: 3

Views: 2158

Answers (1)

helloitsjoe
helloitsjoe

Reputation: 6529

One of the main advantages to create-react-app starting a localhost server is hot reloading.

When you write most modern JavaScript, including React, your code needs to be transpiled (essentially converted to a different version of JS) before the browser can understand it. This is called the build process, which takes all the files in the src directory and bundles them into a single static JS file.

You could do this manually with npm run build, which creates an index.html that you can open in a browser without running a server. But you have to go through 2 part process to see your changes: rebuild and then reload the browser to see your changes.

create-react-app is built so that it watches for changes in your files, updates the built JS whenever you hit save, and then restarts the server, loading your changes automatically.

By running a server on localhost, create-react-app can update your page instantly every time you save, without you manually rebuilding OR refreshing the page. Hot reloading!

Upvotes: 4

Related Questions