Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Full Stack FastAPI, React, and MongoDB

You're reading from   Full Stack FastAPI, React, and MongoDB Fast-paced web app development with the FARM stack

Arrow left icon
Product type Paperback
Published in Aug 2024
Publisher Packt
ISBN-13 9781835886762
Length 312 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (4):
Arrow left icon
Shrey Batra Shrey Batra
Author Profile Icon Shrey Batra
Shrey Batra
Rachelle Palmer Rachelle Palmer
Author Profile Icon Rachelle Palmer
Rachelle Palmer
Shubham Ranjan Shubham Ranjan
Author Profile Icon Shubham Ranjan
Shubham Ranjan
Marko Aleksendrić Marko Aleksendrić
Author Profile Icon Marko Aleksendrić
Marko Aleksendrić
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Chapter 1: Web Development and the FARM Stack 2. Chapter 2: Setting Up the Database with MongoDB FREE CHAPTER 3. Chapter 3: Python Type Hints and Pydantic 4. Chapter 4: Getting Started with FastAPI 5. Chapter 5: Setting Up a React Workflow 6. Chapter 6: Authentication and Authorization 7. Chapter 7: Building a Backend with FastAPI 8. Chapter 8: Building the Frontend of the Application 9. Chapter 9: Third-Party Services Integration with FastAPI and Beanie 10. Chapter 10: Web Development with Next.js 14 11. Chapter 11: Useful Resources and Project Ideas 12. Index 13. Other Books You May Enjoy

The frontend – React

The changes in the world of the web are most visible when talking about the frontend—the part of the website that is facing the users. Tim Berners-Lee made the first HTML specification public in 1991, and it consisted of text and under 20 tags. In 1994, CSS was introduced and the web started looking a little nicer. Legend has it that the new browser scripting language called Mocha was created in just 10 days—that was in 1995. Later, this language went through numerous changes and became what we know today as JavaScript—a powerful and fast language that, with the advent of Node.js, was able to conquer the servers, too.

In May 2013, React was presented in the US and the web development world was able to witness virtual DOM, one-way data flow, the Flux pattern, and more.

This is a bit of history to just try and provide some context and continuity because web development, like any other creative human activity, rarely moves in quantum leaps. Usually, it moves in steps that enable users to resolve the issues that they are facing. It would be unfair not to mention Vue.js, which is an excellent choice for building frontends that also sports an entire ecosystem of libraries, and Svelte.js, which offers a radical shift in building UIs in the sense that the UI is compiled, and the bundled size is significantly smaller.

Why use React?

Interactive, attractive, fast, and intuitive UIs are a necessity for any public-facing web application. It is possible, though very difficult, to achieve most or every functionality that even a simple web application is expected to provide using just plain JavaScript. FastAPI is more than capable of serving HTML (and static files, such as JavaScript or CSS) using any compatible templating engine (the most widely used in the Python world is probably Jinja2), but we and the users want more.

Compared to other frameworks, React is small. It isn’t even considered a framework, but a library— actually, a couple of libraries. Still, it is a mature product with over 10 years of development behind it, created for the needs of Facebook and utilized by the biggest companies such as Uber, X (formally known as Twitter), and Airbnb.

This book does not explore React in depth because we want to focus on how all the different parts of the FARM stack connect and fit within the bigger picture. Additionally, 81% of developers already use React2 and are familiar with its features, so we assume our readers have a level of familiarity with this framework already.

Most developers want a streamlined and structured way of building UIs. React enables developers to create dynamic applications in a much easier way by relying on JSX—a mix of JavaScript and XML that has an intuitive tag-based syntax and provides developers with a way to think of the application in terms of components that go on to form other, more complex, components, thus breaking the process of crafting complex UI and interactions into smaller, more manageable steps.

The main benefits of using React as a frontend solution can be summarized as follows:

  • Performance: By using the React virtual DOM, which operates in memory, React apps provide smooth and fast performance.
  • Reusability: Since the app is built by using components that have their own properties and logic, you can write out components once and then reuse them as many times as needed, cutting down development time and complexity.
  • Ease of use: This is always a bit subjective but React is easy to get started. Advanced concepts and patterns require some level of proficiency, but even novice developers can reap immediate benefits just from the possibility of splitting the application frontend into components and then using them like LEGO bricks.

React and frameworks based on React empower you, as a developer, to create single-page applications that have a desktop-like look and feel, but also server-side rendering that is beneficial for search engine optimization. Knowing your way around React enables you to benefit from some of today’s most powerful frontend web frameworks such as Next.js, static site generators (such as Gatsby.js), or exciting and promising newcomers (such as React Remix).

In version 16.8, the React library introduced Hooks, which enable developers to use and manipulate the state of the components, along with some other features of React, without the need to use classes. This is a big change that successfully tackles different issues—it enables the reusability of stateful logic between components and simplifies the understanding and management of complex components.

The simplest React Hook is probably the useState Hook. This Hook enables you to have and maintain a stateful value (such as an object, array, or variable) throughout the life cycle of the component, without having to resort to old-school class-based components.

For instance, a very simple component that could be used to filter search results when a user is trying to find the right car might contain the desired brand, model, and a production year range. This functionality would be a great candidate for a separate component—a search component that would need to maintain the state of different input controls, probably implemented as a series of dropdowns. Let’s just see the simplest possible version of this implementation.

The following block of code creates a simple functional component with a single stateful string value—an HTML select element that will update the stateful variable named brand:

import { useState } from “react”;
const Search = () => {
const [brand, setBrand] = useState(“”);
return (
<div>
<div>Selected brand: {brand}</div>
<select onChange={(ev) => setBrand(ev.target.value)}>
<option value=””>All brands</option>
<option value=”Fiat”>Fiat</option>
<option value=”Ford”>Ford</option>
<option value=”Renault”>Renault</option>
<option value=”Opel”>Opel</option>
</select>
</div>
);
};
export default Search;

The bold line is where the Hook magic happens, and it must be within the body of a function. The statement simply creates a new state variable, called brand, and provides you with a setter function that can be used inside the component to set the desired value.

There are many Hooks that solve different problems, and this book will go over the following fundamental ones:

  • Declarative views: In React, you do not have to worry about transitions or mutations of the DOM. React handles everything, and the only thing you have to do is declare how the view looks and reacts.
  • No templating language: React practically uses JavaScript as a templating language (through JSX), so all you have to know in order to be able to use it effectively is some JavaScript, such as array manipulation and iteration.
  • Rich ecosystem: There are numerous excellent libraries that complement React’s basic functionality—from routers to custom Hooks, external library integrations, CSS framework adaptations, and more.

Ultimately, Hooks provide React with a new way of adding and sharing stateful logic across components and can even replace (in simpler cases) the need for Redux or other external state management libraries. Most of the examples shown in this book make use of the Context API—a React feature that enables passing objects and functions down the component tree without the need to pass props through components that do not need it. Coupled with a Hook—the useContext Hook—it provides a straightforward way of passing and maintaining stateful values in every part of the app.

React uses (although it is not imperative) the newest features of functional JavaScript, ES6, and ES7, particularly when it comes to arrays. Working with React improves understanding of JavaScript, and a similar thing could be said of FastAPI and modern Python.

The final piece of the puzzle will be the choice of a CSS library or framework. Currently, in 2024, there are dozens of CSS libraries that play nice with React, including Bootstrap, Material UI, Bulma, and more. Many of these libraries merge with React to become meaningful frameworks of prebuilt customizable and parameterized components. We will use Tailwind CSS as it is simple to set up—and it is intuitive once you get the hang of it.

Keeping the React part to a bare minimum should allow you to focus more on the true protagonists of the story—FastAPI and MongoDB. You can easily replace React, should you wish to do so, be it Svelte.js, Vue.js, or vanilla handcrafted ECMAScript. However, by learning the basics of React (and Hooks), you are embarking on a wonderful web development adventure that will enable you to use and understand many tools and frameworks built on top of React.

Arguably, Next.js is the feature-richest server-side rendering React framework that enables fast development, filesystem-based routing, and more.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime