Contexto
SPA vs Traditional Web Page
Until know everything we have seen serves a specific architecture model. Up to this point, we were creating HTML files, and we were navigating from one HTML file to the next one through links (anchor tags). This style of software architecture is called a ‘multi-page-application’. Any time we want to navigate into a different file, we make an external request to the server and the server responds by serving another static HTML file, exactly like the above image shows. Although this seemed to work quite well until recently , we put a lot of load to our server’s shoulder. Normally we would like to reduce some of this load, and put as much as possible work to the browser, since we have only one server to serve all users, but every user has a dedicated browser.
For that reason, comes another software architecture style to the rescue. The Single Page Applications or SPA’s. The main idea behind this architecture is that the server serves only one HTML file to the client which contains all different react components and versions (we call them ‘routes’) of the same file. Then we put route links instead of normal links that change the route url in the client. Then we specify which component (or JSX elements) are going to be displayed under this url route. This technique has a tremendous advantage since we don’t need to make an external request to the server any time we navigate. Everything happens on the client (browser) side and we don’t need to reload the page. So everything is faster.
Although routing is a powerful feature that comes with almost every client-side js framework these days, there is also a con. In order to serve only one HTML file and include these different versions (routes) that the users is going to probably need during his navigation to our site, we need to fetch everything within the original request. That means that the original request to the server for the one and only HTML file (the index.html probably) is going to contain all the possible routes that the user is going to use or not. Thus the initial request typically is going to be served slower than a MPA (multi-page app).
After that obstacle is surpassed, everything runs smoothly within the browser environment. External requests can additionally be made to the server (AJAX calls etc) but only to fetch and exchange data (mostly to JSON format) and not whole HTML files, as is depicted to the below image. Let’s take a look on how we can implement such a functionality.