In this post, we will look at the React App Startup Process. In other words, what happens behind the scenes when we start a React application?
When we create a new React application using create-react-app, we get a bunch of project files and folders. Basically, it is a ready-to-run application. We can simply go ahead and execute the command npm start. This command creates a dev server and loads our application making it available on localhost:3000.
But the question remains that how does React know which content to render on the screen?
Let’s look at the answer step-by-step.
1 – The index.html File
The first file that gets sent back to the browser when we hit localhost:3000 is the index.html.
This file is available in the public folder of our bootstrapped project. Also, this file is the very base of our project and has the responsibility of loading all the other files that our application needs.
The body section of this file looks as below:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
Important point to note here is the div with id as root.
2 – The Index.js File
The next important file in the whole process of loading our application is the Index.js file. This is the file that basically starts our React application.
This is how it looks:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
ReactDOM.render(<App />, document.getElementById("root"));
We don’t usually need to change this file.
However, this is the first file where React and ReactDOM dependencies are load. The key statement in this file is the call to ReactDOM.render(). Using this function, we basically tell React to render a particular component into the element having id as root in our index.html file. If you recall from above, the id root is assigned to the blank div element in the index.html file. The component that has to be loaded is basically the App Component.
3 – The App Component
Every React application needs some sort of a parent or top-level component. More often than not, this component is known as the App Component.
import React from "react";
function App() {
return (
<div>
<h1>Hello World</h1>
</div>
);
}
export default App;
All other components that we make in React are nested within this component or its child components.
Components are described using JSX. If you don’t know about JSX, it is basically a combination of HTML and Javascript that builds the visual representation of the component. You can read more about JSX in this detailed post.
The point to take away is that the App Component loads all the child components depending on the logic. Ultimately, the overall application renders on the browser.
This is basically a high-level overview of what happens during the React App Startup Process.
If you have any comments or queries, please do mention in the comments section below.
0 Comments