32,39 €
React helps you work smarter, not harder — but to reap the benefits of this popular JavaScript library and its components, you need a straightforward guide that will teach you how to make the most of it.
React 18 Design Patterns and Best Practices will help you use React effectively to make your applications more flexible, easier to maintain, and improve their performance, while giving your workflow a huge boost. With a better organization of topics and knowledge about best practices added to your developer toolbox, the updated fourth edition ensures an enhanced learning experience.
The book is split into three parts; the first will teach you the fundamentals of React patterns, the second will dive into how React works, and the third will focus on real-world applications. All the code samples are updated to the latest version of React and you’ll also find plenty of new additions that explore React 18 and Node 19’s newest features, alongside MonoRepo Architecture and a dedicated chapter on TypeScript.
By the end of this book, you'll be able to efficiently build and deploy real-world React web applications.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 500
React 18 Design Patterns and Best Practices
Fourth Edition
Design, build, and deploy production-ready web applications with React by leveraging industry-best practices
Carlos Santana Roldán
BIRMINGHAM—MUMBAI
React 18 Design Patterns and Best Practices
Fourth Edition
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damage caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Senior Publishing Product Manager: Suman Sen
Acquisition Editor – Peer Reviews: Saby Dsilva
Project Editor: Parvathy Nair
Content Development Editor: Shazeen Iqbal
Copy Editor: Safis Editor
Technical Editor: Srishty Bhardwaj
Proofreader: Safis Editor
Indexer: Rekha Nair
Presentation Designer: Rajesh Shirsath
Developer Relations Marketing Executive: Priyadarshini Sharma
First published: January 2017
Second published: March 2019
Third published: May 2021
Fourth edition: July 2023
Production reference: 3070823
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-80323-310-9
www.packt.com
I would like to dedicate this book to my lovely daughter, Victoria.
– Carlos Santana Roldán
Carlos Santana Roldán is a software engineer with over 16 years of experience in the industry. He is the author of the books React Cookbook and React Design Patterns and Best Practices – Second, Third, and Fourth Editions. Carlos is also the founder of one of the most renowned developers’ communities in Latin America, Series Frontend, where he trains individuals in various web technologies (https://www.youtube.com/@SeriesFrontend).
Roy Derks has been working in web development for the past 15 years. He has founded multiple startups, and worked as a startup CTO and developer advocate for numerous startups. Roy has been using GraphQL, React, and TypeScript since the early days and is seen as a thought leader in the space. In recent years he has published multiple books with Packt Publishing such as React Projects (First and Second Editions) and React and React Native (Third and Fourth Editions).
Jonathan Reeves is a software engineer with over five years of experience. Jonathan has used JavaScript and/or TypeScript for most of his development career, which has included extensive usage of React, GraphQL, and Node with Express. Currently, he is working as a mid-level software engineer in the video game industry using C++ and the .NET tech stack.
First, I would like to thank my wife. Without her patience and help with our children, I would not have been able to review this book in the amount of time necessary. I love you. I would also like to thank my kids for allowing me to review this book in the hopes that sometime soon they will start their journey of learning software development. Ava, and Grayson, Daddy loves you very much.
Join our community’s Discord space for discussion with the author and other readers:
https://packt.link/React18DesignPatterns4e
Preface
Who this book is for
What this book covers
Get in touch
Taking Your First Steps with React
Technical requirements
Differentiating between declarative and imperative programming
How React elements work
Unlearning everything
Understanding JavaScript fatigue
Misconceptions about React
Getting started with React without the fatigue
Advantages of the JavaScript ecosystem
Bye to Create-React-App, welcome to Vite!
Vite as a solution
Summary
Introducing TypeScript
Technical requirements
TypeScript’s features
Converting JavaScript code into TypeScript
Types
Interfaces
Extending interfaces and types
Implementing interfaces and types
Merging interfaces
Enums
Namespaces
Template literals
TypeScript configuration file
Summary
Cleaning Up Your Code
Technical requirements
Using JSX
Babel
Creating our first element
DOM elements and React components
Props
Children
Differences with HTML
Attributes
Style
Root
Spaces
Boolean attributes
Spread attributes
Template literals
Common patterns
Multiline
Multi-properties
Conditionals
Loops
Sub-rendering
Styling code
EditorConfig
Prettier
ESLint
Installation
Configuration
Git Hooks
Functional programming
First-class functions
Purity
Immutability
Currying
Composition
Summary
Exploring Popular Composition Patterns
Technical requirements
Communicating components
Using the children prop
Exploring the container and presentational patterns
Understanding HOCs
Understanding FunctionAsChild
Summary
Writing Code for the Browser
Technical requirements
Understanding and implementing forms
Uncontrolled components
Controlled components
Handling events
Exploring refs
Understanding forwardRef
Implementing animations
Exploring SVG
Summary
Making Your Components Look Beautiful
Technical requirements
CSS in JavaScript
Understanding and implementing inline styles
Using CSS modules
Webpack 5
Setting up a project
Locally scoped CSS
Atomic CSS modules
Implementing styled-components
Summary
Anti-Patterns to Be Avoided
Technical requirements
Initializing the state using properties
Using indexes as a key
Spreading properties on DOM elements
Summary
React Hooks
Technical requirements
Introducing React Hooks
No breaking changes
Using the State Hook
Rules of Hooks
Rule 1: Only call Hooks at the top level
Rule 2: Only call Hooks from React functions
Migrating a class component to React Hooks
Understanding React effects
Understanding useEffect
Firing an effect conditionally
Understanding useCallback, useMemo, and memo
Memoizing a component with memo
Memoizing a value with useMemo
Memoizing a function definition with useCallback
Memoizing a function passed as an argument in effect
Understanding the useReducer Hook
Summary
React Router
Technical requirements
Installing and configuring React Router
Creating our sections
Adding parameters to the routes
React Router v6.4
React Router loaders
Summary
React 18 New Features
Concurrent mode
Automatic batching
Transitions
Suspense on the server
New APIs
createRoot
hydrateRoot
renderToPipeableStream
New Hooks
useId
useTransition
useDeferredValue
useInsertionEffect
Strict mode
Node.js latest features
Experimental Fetch API
Experimental test runner module
Experimental node watch
Node 18 is now Long-Term Support (LTS)
Summary
Managing Data
Technical requirements
Introducing the React Context API
Creating our first context
Wrapping our components with the provider
Consuming context with useContext
Introducing React Suspense with SWR
Introducing SWR
Building a Pokedex!
Testing React Suspense
Redux Toolkit: a modern approach to Redux
Key features
Getting started
Creating a store
Creating a slice
Combining reducers
Connecting components to the store
Integrating the store with a React application
Summary
Server-Side Rendering
Technical requirements
Understanding universal applications
Reasons for implementing SSR
Implementing SEO
A common code base
Better performance
Don’t underestimate the complexity of SSR
Creating a basic example of SSR
Configuring our project from scratch with webpack
Creating the application
Implementing data fetching
Using Next.js to create a React application
Summary
Understanding GraphQL with a Real Project
Technical requirements
Building a backend login system using PostgreSQL, Apollo Server, GraphQL, Sequelize, and JSON Web Tokens
Installing PostgreSQL
Best tools for PostgreSQL database management
Creating our backend project
Configuring our .env file
Creating a basic config file
Configuring Apollo Server
Defining our GraphQL types, queries, and mutations
Scalar types
Queries
Mutations
Merging type definitions
Creating our resolvers
Creating the getUsers query
Creating the getUser query
Creating the mutations
Merging our resolvers
Using the Sequelize ORM
Creating a user model in Sequelize
Connecting Sequelize to a PostgreSQL database
Authentication functions
Creating JWT functions
Creating authentication functions
Defining types and interfaces
Running our project for the first time
Testing GraphQL queries and mutations
Testing model validations and querying users
Performing a login
Building a frontend login system with Apollo Client
Configuring Webpack 5
Configuring our TypeScript
Configuring the Express server
Creating our frontend configuration
Creating the user middleware
Creating JWT functions
Creating our GraphQL queries and mutations
Creating user context to handle login and connected user
Configuring Apollo Client
Creating our app routes
Creating our pages
Creating our login components
Creating our dashboard components
Testing our login system
Summary
MonoRepo Architecture
Technical requirements
Advantages of a monorepository and the problems it solves
Creating a MonoRepo with NPM Workspaces
Implementing TypeScript in our MonoRepo
Creating a devtools package to compile packages with Webpack
Creating a colorful log
Webpack common configuration
Webpack development configuration
Webpack production configuration
Creating the utils package
Creating the API package
Creating a user-shared model
Creating a user-shared GraphQL type and resolver
Creating custom services
Building our service configuration
Creating our custom models
Creating model seeds
Creating our custom GraphQL types and resolvers
Synchronizing our models and starting Apollo Server
Testing our CRM service
Creating the frontend package
Creating our Sites system
Creating our Page Switcher
Creating our Login system
Creating our sites configuration
Putting everything together
Demo time!
Summary
Improving the Performance of Your Applications
Technical requirements
How reconciliation works
Using keys
Optimization techniques
Tools and libraries
Immutability
Babel plugins
Summary
Join our community on Discord
Testing and Debugging
Technical requirements
Understanding the benefits of testing
Painless JavaScript testing with Jest
Testing events
Introducing Vitest
Installing and configuring Vitest
Enabling globals
In-source testing
Using React DevTools
Using Redux DevTools
Summary
Deploying to Production
Technical requirements
Creating our first DigitalOcean Droplet
Signing up to DigitalOcean
Creating our first Droplet
Installing Node.js
Configuring Git and GitHub
Turning off our Droplet
Configuring nginx, PM2, and a domain
Installing and configuring nginx
Setting up a reverse proxy server
Adding a domain to our Droplet
Implementing CircleCI for continuous integration
Adding an SSH key to CircleCI
Configuring CircleCI
Creating environment variables variables in CircleCI
Summary
Other Books You May Enjoy
Index
Cover
Index
React is a revolutionary, open-source JavaScript library that breathes life into web applications by constructing intricate user interfaces from small, isolated chunks known as components. This book serves as a roadmap, guiding you through the wonders of React and enhancing your productivity by introducing an efficient workflow without compromising on quality.
Our journey begins by delving deep into the core of React, gaining a thorough understanding of its internal mechanisms and architecture. With this strong foundation in place, we will guide you towards writing clean and maintainable code, breaking down complex concepts into digestible and manageable chunks.
Continuing our journey, we will uncover the art of building components that aren’t just one-off entities but reusable pieces across your application. We’ll illuminate the path to structuring your applications, making them more organized and manageable. The seemingly daunting task of creating functional forms will become a breeze as we equip you with strategies and techniques to do so effectively.
As we ascend further, we’ll immerse ourselves in styling React components. You’ll learn how to bring your applications to life with aesthetic appeal while ensuring they remain swift and responsive. Moreover, you’ll discover the secrets of enhancing application performance, fine-tuning your components for speed and efficiency.
In the final phase of our journey, we’ll delve into testing methodologies effectively, refining the quality and reliability of your applications. You’ll also gain insight into contributing to React and its thriving ecosystem, joining the ranks of developers who continually drive its evolution.
By the end of this book, the trial-and-error process, the developmental hurdles, and guesswork will be things of the past. You will have harnessed the power of React, equipped with the skills necessary to construct and deploy real-world React web applications with confidence and finesse.
This book is for web developers who want to increase their understanding of React and apply it to real-life app development. Intermediate-level experience with React and JavaScript is assumed.
In Chapter 1, Taking Your First Steps with React, we start our journey to understand React by learning to write declarative code and distinguishing between our components and React’s elements. We also discuss why we combine logic and templates in React, a decision that was controversial initially but ultimately beneficial. Recognizing the potential for feeling overwhelmed in the rapidly evolving world of JavaScript, we suggest taking small, manageable steps to avoid fatigue. We wrap up by introducing the new create-vite tool, preparing you for hands-on coding experience in React.
In Chapter 2, Introducing TypeScript, we’ll learn the basics of TypeScript, including creating simple types, interfaces, using enums, namespaces, and template literals. We’ll also figure out how to set up our first TypeScript configuration file (tsconfig.json) and divide it into two parts - a common part and a specific part, which is particularly handy when working with MonoRepos. After this chapter, you’ll be all set to delve into using JSX/TSX code and explore ways to make your code better in the next chapter. Get ready to use TypeScript to make your React apps easy to work with and maintain.
In Chapter 3, Cleaning Up Your Code, we’ll get to know JSX, including how it’s written and what it can do. We’ll also set up Prettier and ESLint to keep our code neat and prevent mistakes. Plus, we’ll learn about functional programming, which makes our code easier to manage and test. After tidying up our code, we’ll be prepared to go deeper into React and learn how to make components that we can use repeatedly in the next chapter. By adopting good habits, we can build React apps that are simple to manage, grow, and check.
In Chapter 4, Exploring Popular Composition Patterns, we’ll learn how to use “props” to make our reusable components work together better. Using props helps keep our components separate and welldefined. We’ll look at two common ways to organize components: the container and presentational pattern, which keeps the rules and looks of our components separate. We’ll also learn about Higher Order Components (HOCs) for dealing with context without making our components too dependent, and the Function as Child pattern for creating components on-the-fly.
In Chapter 5, Writing Code for the Browser, we’ll look at how React can be used in a web browser to create forms, handle events, and animate SVGs. We’ll learn about the useRef Hook, which is an easy way to reach DOM nodes.
With React’s simple, straightforward approach, managing complex web apps becomes easier. Plus, React allows us to access DOM nodes directly if we need to, which makes it simple to use React with other libraries.
In Chapter 6, Making Your Components Look Beautiful, we’ll dive into styling in React. We’ll start by looking at the problems with making CSS work for big projects, using the experiences of Meta as an example. We’ll learn about how we can write styles directly inside our React components, which keeps our code tidy and easy to read. But we’ll also learn about the limitations of this method and explore another way of styling, called CSS modules, that lets us write CSS in separate files but keep the styles scoped to individual components. Finally, we’ll get to know styled-components, a popular library for styling in React. By the end of this chapter, you’ll have many tools for making your React apps look great.
In Chapter 7, Anti-Patterns to Be Avoided., we’ll talk about four ways of using components that could slow down or mess up our web apps. For each problem, we’ll use an example to show what goes wrong and how to fix it. We’ll learn why using properties to set up the state can cause problems between the state and the properties. We’ll also see how using the wrong “key” attribute can mess up the way React updates components. Lastly, we’ll learn why spreading non-standard properties to DOM elements is a bad idea. Understanding these issues will help us use React more effectively and avoid common mistakes.
In Chapter 8, React Hooks, we’ll have a lot of fun learning about the new React Hooks. We’ll learn how they work, how to use them to get data, and how to change a class component into a Hooks one. We’ll also learn about effects and the differences between memo, useMemo, and useCallback. Finally, we’ll see how the useReducer Hook works and how it’s different from react-redux. All of this will help us make our React components faster and better.
In Chapter 9, React Router, we’ll learn about React Router, a tool we use with React to move between pages in a single-page application. React doesn’t do this on its own, so we use React Router. We’ll find out how to use it to make our app respond to different URLs and manage navigation. By the end of this chapter, you’ll know how React Router works and how to use it in your projects. We’ll learn the differences between the react-router, react-router-dom, and react-router-native packages, how to set up React Router, how to add the <Routes> component, and how to add parameters to the routes.
In Chapter 10, React 18 New Features, we’ll explore the new and improved React 18. It has loads of features that make building cool, interactive apps even easier.
With automatic state update grouping, concurrent rendering, Suspense for getting data, better error handling, and new component types, you can create engaging and fast apps. If you work with React, it’s a good idea to consider upgrading to React 18. We’ll also look at some of the big new features in Node 18 and 19, which can make our web projects even better.
In Chapter 11, Managing Data, we’ll learn about the React Context API and how to use React Suspense with SWR. We’ll learn the basics of the Context API, including creating and using contexts and how the useContext hook makes this even easier. We’ll also look at React Suspense and how it helps us handle loading states better for a smoother user experience. We’ll also learn about SWR, which makes it easier to fetch and cache data with React Suspense. Lastly, we’ll learn how to use the new Redux Toolkit. All these tools will help us build faster and more user-friendly React apps.
In Chapter 12, Server Side Rendering, we’ll finish our journey through server-side rendering (SSR) with React. Now you’ll know how to create an app that uses SSR, and why it can be useful for things like search engine optimization (SEO), social sharing, and improving performance. We’ll learn how to load data on the server and put it into the HTML template so it’s ready for the client-side app when it starts up in the browser. Lastly, we’ll see how tools like Next.js can make setting up SSR in React a lot easier by reducing the amount of extra code and hiding some of the tricky parts.
In Chapter 13, Understanding GraphQL with a Real Project, we’re going to learn about GraphQL, a cool tool that helps us work with APIs and our data more efficiently. Unlike regular REST APIs, GraphQL lets us ask for exactly what we need and nothing more. We’re going to use it to make a simple login and user registration system for a real project. We’ll learn how to install PostgreSQL, set up environment variables with an .env file, set up Apollo Server, make GraphQL queries and mutations, work with resolvers, create Sequelize models, use JWTs, play with the GraphQL Playground, and do authentication. By the end, you’ll know how to use GraphQL in your own projects.
In Chapter 14, MonoRepo Architecture, we’ll talk about something called a “MonoRepo.” Normally, when we build apps, we have one app, one git repository, and one build output. But many organizations use a single repository for all their apps, components, and libraries to make development easier. This is what we call a monorepository. It’s like keeping all your code in one big basket instead of having many little baskets. This makes it easier to keep everything updated and it can save time. We’ll also discuss how a MonoRepo can make it easier to refactor code, improve teamwork, and speed up the process of updating a package dependency without having to publish a new version every time there’s an update.
Chapter 15, Improving the Performance of Your Applications, we will explore techniques to make your apps run smoother and quicker for a better user experience. We’ll delve into how React updates your app’s display and how using keys can aid in this process for improved efficiency. We will discover the importance of well-structured, task-focused components in boosting app performance. We will discuss the concept of immutability and its significance in helping React.memo and shallowCompare work effectively. Toward the end, we will introduce various tools and libraries that can further speed up your applications. This chapter aims to equip you with valuable knowledge to enhance the speed and performance of your apps.
In Chapter 16, Testing and Debugging, we’re going to learn all about testing. You’ll find out why testing is important and explore different tools and techniques for checking if our React components are working as they should. We’ll work with libraries like React Testing Library and Jest to write and run tests, and even see how to test complex parts of our application like high-order components or forms with lots of fields. Plus, we’ll learn how to use tools like React DevTools and Redux DevTools to help us develop better apps. By the end of this chapter, you’ll have a solid grasp of how to keep your app working well through effective testing.
In Chapter 17, Deploying to Production, we’re going to take the React app you’ve built and share it with the world! We’ll use a cloud service called DigitalOcean to do this. You’ll learn how to use Node.js and nginx to get your app up and running on a server, and we’ll use an Ubuntu server from DigitalOcean for this purpose. We’ll walk you through how to set up a DigitalOcean Droplet, configure it, and link it to your domain. We’re also going to introduce you to CircleCI, which is a tool that helps you automatically make sure your app is always ready for users, no matter how many changes you make. By the end of this chapter, you’ll have your app live on the internet for everyone to see!
To master React, you need to have a fundamental knowledge of JavaScript and Node.js. This book is mostly targeted at web developers, and, at the time of writing, the following assumptions were made of the reader:
The reader knows how to install the latest version of Node.js.The reader is an intermediate developer who can understand JavaScript ES6 syntax.The reader has some experience of CLI tools and Node.js syntax.The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/React-18-Design-Patterns-and-Best-Practices-Fourth-Edition/.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/o1WtB.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: “After you create this util, you need to create the index.ts file at packages/utils/src/index.ts."
A block of code is set as follows:
{ "name":"api", "version":"1.0.0", "main":"index.js", "author":"", "license":"ISC"}Any command-line input or output is written as follows:
cd packages/api npm init -yBold: Indicates a new term, an important word, or words that you see on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: “The first package we need to create to be able to compile other packages is called devtools.”
Warnings or important notes appear like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packtpub.com/submit-errata, click Submit Errata, and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.
Once you’ve read React 18 Design Patterns and Best Practices, Fourth Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/978-1-80323-310-9
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly