Purpose: React is designed for single-page applications (SPA), downloaded with their components in one big bundle into memory. The application we built in Exercise 5.2A doesn't behave that way. It behaves like a classic web application, refreshing the page each time a link is clicked. If we leave it this way, it is more wasteful than the classic multi-page application (MPA) approach we have followed, as will be demonstrated below. In this exercise, we begin to learn avoid needless server bundle reloads using state and lifecycle methods.
To appreciate the solution, we must first see the problem. Start with the React App you built in Exercise 5.2A, running on the React dev server. Open the Network tab in Chrome Developer Tools. Load (or refresh) the page: localhost:5173. You should immediately notice that a lot more items are loaded than in the static version of this page. Several are React helper scripts that do not come from your code, but please go through and look at each item that is from your code, summarized below.
| localhost |
Click on "Response" subtab. Compare contents to "index.html" in your React project. You will see it is the same, except for a little extra inserted javascript, to instruct your Browser to load React helper scripts. Click on the "Headers" subtab. You will see the Browser simply requested "localhost:5173" URL (with no other data). The React dev server is running on this port and receives this request. The React dev server works mostly like a general web server, with a few small tweaks. |
| bootstrap.min.css | Your project's index.html asks for Bootstrap CSS. |
| bootstrap.min.js | Your project's index.html asks for Bootstrap JS. |
| main.jsx?t=<timestamp> |
Click on "Response" subtab. Compare contents to "src/main.jsx" in your React project. You will see it comes from the contents of this file, but with several small changes such as absolutized paths and extra parameters. All React code starts with index.html and then goes to main.jsx. Notice that it imports main.jsx imports App.jsx, among other things. Also, look at the very bottom, where there is a commend about "sourceMappingURL". Each JSX file has one. Source maps help debugging in dev mode. |
| index.css | The content is from your "src/index.css" file, but you will see it is modified. |
| App.jsx?t=<hash-value> | App.jsx is imported by main.jsx. Click on "Response" and notice that it has absolutized paths and extra parameters added in, and that it imports Layout.jsx, Home.jsx, Abouts.jsx, and Contact.jsx in turn. |
| Layout.jsx?t=<hash-value> | Layout.jsx is imported by App.jsx. |
| Home.jsx | Home.jsx is imported by App.jsx. |
| About.jsx | About.jsx is imported by App.jsx. |
| Contact.jsx | Contact.jsx is imported by App.jsx. |
| Nav.jsx | Nav.jsx is imported by Layout.jsx. |
| Footer.jsx | Footer.jsx is imported by Layout.jsx. |
Reflect and Test. Now, click on About and Contact. You will notice that the entire bundle (main.jsx, App.jsx, Layout.jsx, Home.jsx, About.jsx, Contact.jsx, Nav.jsx, and Footer.jsx, and helper files) loads each time a link is clicked.
Run Build: Before we start exploring how to make React load only once and avoid refreshing the entire bundle, you need to Experience the React Bundle after fully transpiling into vanilla HTML and JS. Run "pnpm run build" to create the dist folder, then run that folder somewhere in your htdocs folder through XAMPP. Open Chrome Developer Tools > Network tab and see how the built version shows.
Fewer Files: You will notice there are fewer files loaded. The contents of your index.html still loads first. Then, a single index-<hash-value>.js file and a single index-<hash-value>.css file are loaded. If you look inside index-<hash-value>.js, you will see that it uses short, cryptic variable names and is basically hard to follow, so hard that some compare it to compiling C code into machine code, even though it is really just ordinary javascript that the Browser can read. Many call this "transpiling" (translation that looks and feels like compiling).
Same Action: The transpiled Javascript does basically the exact same things in the exact same order as the React dev server. Although the number of files is smaller, the problem is the same: Refreshing a page loads the entire application, all pages and components, instead of just one page at a time.
Avoiding Refresh: Since it is wasteful to reload the entire bundle every time a link is clicked, we should change the way the nav links work. A true SPA does loads the bundle only once (all pages and components), then finds a way to stay on the front end using Javascript instead of server requests, keeping server communication to a minimum. There are many ways to do this, but React's main way is to set up "state variables." When you set up a state variable, React forces the component to re-render whenever that state variable changes.
Using State Variables: We will change the "route" variable, which currently reads window.location.pathname, into a state variable, using the useState function. The syntax is a little odd, shown in the example below (and note that an import statement is required). In addition to creating the "route" variable, it creates a setRoute function to set its value:
Passing the Update Function: Now, whenever setRoute is called, the App component will re-render. Since we want to change the <a href> links, we need to pass the setRoute function as a prop (this is simple enough, since any variable, simple or complex, including a function, can be passed as a prop).
Go to the Nav Bar:
Sidenote about the Cursor: You may notice that the <a> links no longer turn the cursor into a pointer after we removed the href attribute. This problem can be solved easily enough with CSS, but we will leave it for now since we will use a better method to solve the problem in the next few exercises.
Older-Style State Variables: Before 2019, the useState function did not exist. The normal way to add "state variables" to React components was to use "class components." The syntax is much easier to understand, but a lot less concise, which is why it is less popular today. Instead of defining a function, you would define a class that inherits the React "Component" class, as follows:
Ponder and Test: Take a moment to study the code above to understand what is happening. Temporarily change your App.jsx to match (you may copy and paste), but keep your old code to restore after this exercise. The JSX <App /> would translate to React creating an instance of the App class to be the App component. The Component class, which it inherits, has all the machinery necessary to mount, update, and unmount on the DOM whenever the variables in this.state change.
Lifecycle Methods: One more important feature of class components is "lifecycle methods," with the following names:
How to Use Lifecycle Methods: The Component class calls these methods when the component mounts, unmounts, or updates. Programmers could then override them using polymorphism to create a sort of event-driven programming, as shown below. An example of this is below. Run it to see exactly when these methods are called.
Sidenote: Called Twice: You may notice that the functions are called twice (two alerts). That is because of two things: (1) your React app is in "strict mode" (see main.jsx), and (2) you are running the React Dev server. Strict mode with the dev server always follows a mount-unmount-mount strategy that forces components to render twice. The point of doing this is to help developers notice unintended bugs that might occur if their components re-render at a time they did not expect, since React is always doing a lot of rendering and re-rendering. Some developers found this behavior helpful when introduced, some found it frustrating, but it is the state of things in the current version of React.
Sidenote: Legacy Lifecycle Methods: In practice, people rarely used componentWillMount, componentWillReceiveProps, or componentWillUpdate, so these became legacy, but it is common to see componentDidMount, componentWillUnmount, and shouldComponentMount in legacy React code.
Compare with Functional Components: Now that you have a basic understanding of how state and lifecycle work in class components, it may help to understand how useState works in functional components. The idea is that useState always creates a state variable and a function that updates it. The state variable is a "const" because it does not change until the component is torn down and re-created. In the next exercise, we will explore "hooks", which are the functional component replacement for lifecycle methods like componentDidMount() and componentWillUnmount().