35,99 €
Over the years, React and React Native has proven itself among JavaScript developers as a popular choice for a complete and practical guide to the React ecosystem. This fourth edition comes with the latest features, enhancements, and fixes to align with React 18, while also being compatible with React Native. It includes new chapters covering critical features and concepts in modern cross-platform app development with React.
From the basics of React to popular components such as Hooks, GraphQL, and NativeBase, this definitive guide will help you become a professional React developer in a step-by-step manner. You'll begin by learning about the essential building blocks of React components. As you advance through the chapters, you'll work with higher-level functionalities in application development and then put your knowledge to work by developing user interface components for the web and native platforms. In the concluding chapters, you'll learn how to bring your application together with robust data architecture.
By the end of this book, you'll be able to build React applications for the web and React Native applications for multiple mobile platforms.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 487
Veröffentlichungsjahr: 2022
Build cross-platform JavaScript applications with native power for the web, desktop, and mobile
Adam Boduch
Roy Derks
Mikhail Sakhniuk
BIRMINGHAM—MUMBAI
Copyright © 2022 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 authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages 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.
Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Aaron Tanna
Senior Editor: Hayden Edwards
Content Development Editor: Rashi Dubey
Technical Editor: Joseph Aloocaran
Copy Editor: Safis Editing
Project Coordinator: Rashika Ba
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Ponraj Dhandapani
Marketing Coordinator: Anamika Singh
First published: March 2017
Second edition: September 2018
Third edition: April 2020
Fourth edition: May 2022
Production reference: 1270522
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80323-128-0
www.packt.com
For Jason, Simon, and Kevin
– Adam Boduch
For every developer out there that needs a friend on their programming journey
– Roy Derks
For my wife, Anna, and daughter, Polina
– Mikhail Sakhniuk
Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Thanks to the React team for providing the web with this fantastic tool.
Roy Derks is a serial start-up CTO, international speaker, and author from the Netherlands. He has been working with React, React Native, and GraphQL since 2016. You might know him from the book React Projects – Second Edition, which was released by Packt earlier this year. Over the last few years, he has inspired tens of thousands of developers worldwide through his talks, books, workshops, and courses.
Mikhail Sakhniuk is a software engineer who is highly proficient in JavaScript, React, and React Native. He has more than 6 years of experience in developing web and mobile applications. He has worked for start-ups, fintech companies, and product companies with more than 30 million users. Currently, Mikhail is working as a senior frontend engineer. In addition, he owns and maintains a number of open source projects. He also shares his knowledge and experience through books and articles.
I'd like to thank the entire JavaScript community for creating, maintaining, and using a thousand libraries and tools that make the web faster, bigger, and more accessible.
Kirill Ezhemenskii is an experienced software engineer, frontend and mobile developer, solution architect, and CTO at a healthcare company. He's a functional programming advocate and an expert in the React Stack, GraphQL, and TypeScript. Kirill is also a React Native mentor.
Sunki Baek is an experienced frontend developer who primarily works with React Native to develop cross-platform applications. His React Native journey started in 2016, shortly after React Native was introduced—his first project was to create an e-commerce app with a chat feature. Ever since then, he has been involved in e-commerce, online-to-offline commerce, and food technology projects. Currently, he is working as a senior mobile developer in the Restaurant Live Order team at SkipTheDishes.
Andrew Baisden is a software developer who has experience working across different technical stacks. Primarily skilled as a JavaScript developer, he is also familiar with the programming languages Python and C#. He has a university degree and has spent a lot of time self-training to expand his knowledge and skillset. Technical writing and content creation are two other areas where he excels. Many of his articles have been shared across social media and are used as motivation and essential resources for other developers and aspiring developers who are trying to break into the industry. With a growing audience of over 5,000 members, Andrew continues to add value wherever he goes.
Over the years, React and React Native has proven itself among JavaScript developers as a popular choice for a complete and practical guide to the React ecosystem. This fourth edition comes with the latest features, enhancements, and fixes to align with React 18, while also being compatible with React Native. It includes new chapters covering critical features and concepts in modern cross-platform app development with React.
From the basics of React to popular components such as Hooks, GraphQL, and NativeBase, this definitive guide will help you become a professional React developer in a step-by-step manner.
You'll begin by learning about the essential building blocks of React components. As you advance through the chapters, you'll work with higher-level functionalities in application development and then put your knowledge to work by developing user interface components for the web and native platforms. In the concluding chapters, you'll learn how to bring your application together with robust data architecture.
By the end of this book, you'll be able to build React applications for the web and React Native applications for multiple platforms - web, mobile, and desktop with confidence.
This book is for any JavaScript developer who wants to start learning how to use React and React Native for mobile and web application development. No prior knowledge of React is required; however, working knowledge of JavaScript is necessary to be able to follow along with the content covered.
Chapter 1, Why React?, describes what React is and why you want to use it to build your application.
Chapter 2, Rendering with JSX, teaches the basics of JSX, the markup language used by React components.
Chapter 3, Context Properties, State, and Context, introduces the core mechanisms of passing data around your React application.
Chapter 4, Getting Started with Hooks, shows how React Hooks can be used to extend the behavior of components.
Chapter 5, Event Handling, the React Way, gives an overview of how events are handled by React components.
Chapter 6, Crafting Reusable Components, guides you through the process of refactoring components by example.
Chapter 7, The React Component Life Cycle, describes the various phases that React components go through and why it's important for React developers.
Chapter 8, Validating Component Properties, shows you how to ensure that React component property values are as expected.
Chapter 9, Handling Navigations with Routes, provides plenty of examples of how to set up routing for your React web app.
Chapter 10, Code Splitting Using Lazy Components and Suspense, introduces code-splitting techniques that result in smaller, more efficient applications.
Chapter 11, Server-Side React Components, teaches you how to use Next.js to build large-scale React applications that render content on a server and a client.
Chapter 12, User Interface Framework Components, gives an overview of how to get started with MUI, a React component library for building UIs.
Chapter 13, High-Performance State Updates, goes into depth on the new features in React 18 that allow for efficient state updates and a high-performing application.
Chapter 14, Why React Native?, describes what the React Native library is and the differences between native mobile development.
Chapter 15, React Native under the Hood, gives an overview of the architecture of React Native.
Chapter 16, Kick-Starting React Native Projects, teaches you how to start a new React Native project.
Chapter 17, Building Responsive Layouts with Flexbox, describes how to create a layout and add styles.
Chapter 18, Navigating between Screens, shows the approaches to switching between screens in an app.
Chapter 19, Rendering Item Lists, describes how to implement lists of data in an application.
Chapter 20, Showing Progress, shows you how to handle process indications and progress bars.
Chapter 21, Geolocation and Maps, guides you on how to track geolocation and add a map to an app.
Chapter 22, Collecting User Input, teaches you how to create forms.
Chapter 23, Displaying Modal Screens, teaches you how to create dialog modals.
Chapter 24, Responding to User Gestures, provides examples of how to handle user gestures.
Chapter 25, Using Animations, describes how to implement animations in an app.
Chapter 26, Controlling Image Display, gives an overview of how to render images in a React Native app.
Chapter 27, Going Offline, shows how to deal with an app when a mobile phone doesn't have an internet connection.
Chapter 28, Selecting Native UI Components Using NativeBase, teaches you how to create an application using the NativeBase UI library.
Chapter 29, Handling Application State, shows you how to handle application state for both web and mobile apps.
Chapter 30, Why GraphQL?, describes what GraphQL is and how to use it.
Chapter 31, Building a React GraphQL App, shows how to handle GraphQL in React and React Native apps.
This book assumes you have a basic understanding of the JavaScript programming language. It also assumes that you'll be following along with the examples, which require a command-line terminal, a code editor, and a web browser.
The requirements for learning React Native are the same as for React development, but to run an app on a real device, you will need an Android or iOS smartphone. In order to run iOS apps in the simulator, you will need a Mac computer.
Each chapter has its own folder in the code repository, and each example runs independently of the others. Generally speaking, you can use npm install and npm start to run each example. Check the README files in each folder for more specific instructions pertaining to each specific example.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/React-and-React-Native-4th-Edition. If there's an update to the code, it will be updated in the GitHub repository.
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 and diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781803231280_ColorImages.pdf.
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "You have the actual routes declared as <Route> elements."
A block of code is set as follows:
export default function First() { return <p>Feature 1, page 1</p>;}When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
export default function List({ data, fetchItems, refreshItems, isRefreshing }) { return ( <FlatList data={data} renderItem={({ item }) => <Text style={styles.item}>{item.value}</Text>} onEndReached={fetchItems} onRefresh={refreshItems} refreshing={isRefreshing} /> );}Any command-line input or output is written as follows:
npm install @react-navigation/bottom-tabs @react-navigation/drawer
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "The Container Component will typically contain one direct child."
Tips or Important Notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
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 would report this to us. Please visit www.packtpub.com/support/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 authors.packtpub.com.
ii Preface
Preface iii
iv Preface
Preface
In this part, we will cover the fundamentals of React tools and concepts, applying them to build high-performance web apps.
In this part, we will cover the following chapters:
Chapter 1, Why React?Chapter 2, Rendering with JSX Chapter 3, Context Properties, State, and ContextChapter 4, Getting Started with HooksChapter 5, Event Handling, the React WayChapter 6, Crafting Reusable ComponentsChapter 7, The React Component Life CycleChapter 8, Validating Component PropertiesChapter 9, Handling Navigations with RoutesChapter 10, Code Splitting Using Lazy Components and SuspenseChapter 11, Server-Side React ComponentsChapter 12, User Interface Framework ComponentsChapter 13, High-Performance State UpdatesIf you're reading this book, you probably know what React is. If not, don't worry. I'll do my best to keep philosophical definitions to a minimum. However, this is a long book with a lot of content, so I feel that setting the tone is an appropriate first step. Yes, the goal is to learn React and React Native. But it's also to put together a lasting architecture that can handle everything we want to build with React today and in the future.
This chapter starts with a brief explanation of why React exists. Then, we'll think about the simplicity of React and how it is able to handle many of the typical performance issues faced by web developers. Next, we'll go over the declarative philosophy of React and the level of abstraction that React programmers can expect to work with. Finally, we'll touch on some of the major features of React.
Once you have a conceptual understanding of React and how it solves problems with UI development, you'll be better equipped to tackle the remainder of the book. This chapter will cover the following topics:
What is React?React featuresWhat's new in React 18?I think the one-line description of React on its home page (https://reactjs.org/) is concise and accurate:
"A JavaScript library for building user interfaces."
It's a library for building User Interfaces (UIs). This is perfect because, as it turns out, this is all we want most of the time. I think the best part about this description is everything that it leaves out. It's not a mega framework. It's not a full-stack solution that's going to handle everything from the database to real-time updates over WebSocket connections. We might not actually want most of these prepackaged solutions. If React isn't a framework, then what is it exactly?
React is generally thought of as the view layer in an application. You might have used a library such as Handlebars or jQuery in the past. Just as jQuery manipulates UI elements and Handlebars templates are inserted into a page, React components change what the user sees. The following diagram illustrates where React fits in our frontend code:
Figure 1.1 – The layers of a React application
This is all there is to React – the core concept. Of course, there will be subtle variations to this theme as we make our way through the book, but the flow is more or less the same. We have some application logic that generates some data. We want to render this data to the UI, so we pass it to a React Component, which handles the job of getting the HTML into the page.
You may wonder what the big deal is; React appears to be yet another rendering technology. We'll touch on some of the key areas where React can simplify application development in the remaining sections of the chapter.
React doesn't have many moving parts to learn about and understand. Internally, there's a lot going on, and we'll touch on these things throughout the book. The advantage of having a small API to work with is that you can spend more time familiarizing yourself with it, experimenting with it, and so on. The opposite is true of large frameworks, where all of your time is devoted to figuring out how everything works. The following diagram gives you a rough idea of the APIs that we have to think about when programming with React:
Figure 1.2 – The simplicity of the React API
React is divided into two major APIs:
The React Component API: These are the parts of the page that are rendered by the React DOM.React DOM: This is the API that's used to perform the rendering on a web page.Within a React component, we have the following areas to think about:
Data: This is data that comes from somewhere (the component doesn't care where) and is rendered by the component.Lifecycle: This consists of methods or Hooks that we implement to respond to the component's entering and exiting phases of the React rendering process as they happen over time – for example, one phase of the life cycle is when the component is about to be rendered.Events: These are the code that we write for responding to user interactions.JSX: This is the syntax of React components used to describe UI structures.Don't fixate on what these different areas of the React API represent just yet. The takeaway here is that React, by nature, is simple. Just look at how little there is to figure out! This means that we don't have to spend a ton of time going through API details here. Instead, once you pick up on the basics, we can spend more time on nuanced React usage patterns that fit in nicely with declarative UI structures.
React newcomers have a hard time getting to grips with the idea that components mix in markup with their JavaScript in order to declare UI structures. If you've looked at React examples and had the same adverse reaction, don't worry. Initially, we're all skeptical of this approach, and I think the reason is that we've been conditioned for decades by the separation of concerns principle. This principle states that different concerns, such as logic and presentation, should be separate from one another. Now, whenever we see things mixed together, we automatically assume that this is bad and shouldn't happen.
The syntax used by React components is called JSX (JavaScript XML). A component renders content by returning some JSX. The JSX itself is usually HTML markup, mixed with custom tags for React components. The specifics don't matter at this point; we'll go into detail in the coming chapters. What's groundbreaking about the declarative JSX approach is that we don't have to perform little micro-operations to change the content of a component.
Important Note
Although I won't be following the convention in this book, some React developers prefer the .jsx extension instead of .js for their components.
For example, think about using something such as jQuery to build your application. You have a page with some content on it, and you want to add a class to a paragraph when a button is clicked. Performing these steps is easy enough. This is called imperative programming, and it's problematic for UI development. While this example of changing the class of an element is simple, real applications tend to involve more than three or four steps to make something happen.
React components don't require you to execute steps in an imperative way. This is why JSX is central to React components. The XML-style syntax makes it easy to describe what the UI should look like – that is, what are the HTML elements that this component is going to render? This is called declarative programming and is very well suited for UI development. Once you've declared your UI structure, you need to specify how it changes over time.
Another area that's difficult for React newcomers to grasp is the idea that JSX is like a static string, representing a chunk of rendered output. This is where time and data come into play. React components rely on data being passed into them. This data represents the dynamic parts of the UI – for example, a UI element that's rendered based on a Boolean value could change the next time the component is rendered. Here's a diagram illustrating the idea:
Figure 1.3 – React components changing over time
Each time the React component is rendered, it's like taking a snapshot of the JSX at that exact moment in time. As your application moves forward through time, you have an ordered collection of rendered UI components. In addition to declaratively describing what a UI should be, re-rendering the same JSX content makes things much easier for developers. The challenge is making sure that React can handle the performance demands of this approach.
Using React to build UIs means that we can declare the structure of the UI with JSX. This is less error-prone than the imperative approach of assembling the UI piece by piece. However, the declarative approach does present a challenge –performance.
For example, having a declarative UI structure is fine for the initial rendering because there's nothing on the page yet. So, the React renderer can look at the structure declared in JSX and render it in the DOM browser.
Important Note
The Document Object Model (DOM) represents HTML in the browser after it has been rendered. The DOM API is how JavaScript is able to change content on a page.
This concept is illustrated in the following diagram:
Figure 1.4 – How JSX syntax translates to HTML in the browser DOM
On the initial render, React components and their JSX are no different from other template libraries. For instance, Handlebars will render a template to HTML markup as a string, which is then inserted into the browser DOM. Where React is different from libraries such as Handlebars is when data changes and we need to re-render the component. Handlebars will just rebuild the entire HTML string, the same way it did on the initial render. Since this is problematic for performance, we often end up implementing imperative workarounds that manually update tiny bits of the DOM. We end up with a tangled mess of declarative templates and imperative code to handle the dynamic aspects of the UI.
We don't do this in React. This is what sets React apart from other view libraries. Components are declarative for the initial render, and they stay this way even as they're re-rendered. It's what React does under the hood that makes re-rendering declarative UI structures possible.
React has something called the virtual DOM, which is used to keep a representation of the real DOM elements in memory. It does this so that each time we re-render a component, it can compare the new content to the content that's already displayed on the page. Based on the difference, the virtual DOM can execute the imperative steps necessary to make the changes. So, not only do we get to keep our declarative code when we need to update the UI but React will also make sure that it's done in a performant way. Here's what this process looks like:
Figure 1.5 – React transpiles JSX syntax into imperative DOM API calls
Important Note
When you read about React, you'll often see words such as diffing and patching. Diffing means comparing old content with new content to figure out what's changed. Patching means executing the necessary DOM operations to render the new content.
As with any other JavaScript library, React is constrained by the run-to-completion nature of the main thread. For example, if the React internals are busy diffing content and patching the DOM, the browser can't respond to user input. As you'll see in the last section of this chapter, changes were made to the internal rendering algorithms in React 16 to mitigate these performance pitfalls. With performance concerns addressed, we need to make sure that we're confident that React is flexible enough to adapt to different platforms that we might want to deploy our apps to in the future.
Another topic I want to cover at a high level before we dive into React code is abstraction.
In the preceding section, you saw how JSX syntax translates to low-level operations that update our UI. A better way to look at how React translates our declarative UI components is via the fact that we don't necessarily care what the render target is. The render target happens to be the browser DOM with React, but it isn't restricted to the browser DOM.
React has the potential to be used for any UI we want to create, on any conceivable device. We're only just starting to see this with React Native, but the possibilities are endless. I personally will not be surprised if React Toast becomes a thing, targeting toasters that can singe the rendered output of JSX onto bread. The abstraction level with React is at the right level, and it's in the right place.
The following diagram gives you an idea of how React can target more than just the browser:
Figure 1.6 – React abstracts the target rendering environment from the components that we implement
From left to right, we have React Web (just plain React), React Native, React Desktop, and React Toast. As you can see, to target something new, the same pattern applies:
Implement components specific to the target.Implement a React renderer that can perform the platform-specific operations under the hood.This is, obviously, an oversimplification of what's actually implemented for any given React environment. But the details aren't so important to us. What's important is that we can use our React knowledge to focus on describing the structure of our UI on any platform.
Important Note
React Toast will probably never be a thing, unfortunately.
Now that you understand the role of abstractions in React, let's see what's new in React 18.
The examples in this book are based on React 18. This release doesn't introduce sweeping API changes the way React 16 did. There are, however, two notable changes that we'll cover in more depth in Chapter 13, High-Performance State Updates.
Batching state updates together drastically improves the performance of React applications because it reduces the number of renders to be performed. React has always had the ability to batch multiple state updates into one state update, but it was limited by where this could happen. Specifically, you could only batch state updates together inside event handler functions. The problem here is that most of our state update code runs in an asynchronous way that prevents automatic batching from happening.
React 18 removes this barrier and allows for automatic state update batching to happen anywhere. In Chapter 13, High-Performance State Updates, you'll see examples that compare how this worked prior to React 18 and what you can expect now.
React 18 introduces the notion of a state transition. The idea with state transitions is that the less important state updates that take place in your application should have lower priority than state updates that should happen immediately. In Chapter 13, High-Performance State Updates, we'll explore the new APIs that make setting state update priority a reality in React 18.
It might not seem like much has changed in React 18, but the two major areas that we'll cover have far-reaching consequences for how React applications are implemented going forward. Existing React APIs for this version have mostly been left unchanged so that the React community can quickly adopt this latest major version upgrade without any friction.
In this chapter, you were introduced to React at a high level. React is a library, with a small API, used to build UIs. Next, you were introduced to some of the key concepts of React. We discussed the fact that React is simple because it doesn't have a lot of moving parts. Next, we looked at the declarative nature of React components and JSX. Then, you learned that React takes performance seriously and that this is how we're able to write declarative code that can be re-rendered over and over. Next, you learned about the idea of render targets and how React can easily become the UI tool of choice for all of them. Lastly, I gave you a rough overview of what's new in React 18.
That's enough introductory and conceptual stuff for now. As we make our way toward the end of the book, we'll revisit these ideas. For now, let's take a step back and nail down the basics, starting with JSX.
Take a look at the following links for more information:
React: https://reactjs.org/React 18: https://reactjs.org/blog/2021/06/08/the-plan-for-react-18.html