React and React Native: Build cross-platform JavaScript and TypeScript apps for the web, desktop, and mobile
By Mikhail Sakhniuk, Adam Boduch and Roy Derks
()
Related to React and React Native
Related ebooks
Modern Full-Stack React Projects: Build, maintain, and deploy modern web apps using MongoDB, Express, React, and Node.js Rating: 0 out of 5 stars0 ratingsSpring Boot 3.0 Crash Course Rating: 0 out of 5 stars0 ratingsThe JavaScript Journey: From Basics to Full-Stack Mastery Rating: 0 out of 5 stars0 ratingsWebSocket Essentials – Building Apps with HTML5 WebSockets Rating: 0 out of 5 stars0 ratingsUltimate Node.js for Cross-Platform App Development Rating: 0 out of 5 stars0 ratingsGraph Data Science with Python and Neo4j Rating: 0 out of 5 stars0 ratingsThe Lindahl Letter: 3 Years of AI/ML Research Notes Rating: 0 out of 5 stars0 ratingsOpenFlow Cookbook Rating: 5 out of 5 stars5/5An iOS Developer's Guide to SwiftUI: Design and build beautiful apps quickly and easily with minimum code Rating: 0 out of 5 stars0 ratingsModern Web Development with Go Rating: 0 out of 5 stars0 ratingsData Visualization with D3 4.x Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsJava EE 7 First Look Rating: 0 out of 5 stars0 ratingsMastering OpenCV with Python Rating: 0 out of 5 stars0 ratingsMastering Secure Java Applications: Navigating security in cloud and microservices for Java (English Edition) Rating: 0 out of 5 stars0 ratingsDesigning deep learning systems: Software engineering, #1 Rating: 0 out of 5 stars0 ratingsAI Unleashed: Strategies for Business Success Through Automation in 2025 Rating: 0 out of 5 stars0 ratingsHypermedia Systems Rating: 0 out of 5 stars0 ratingsInstant HTML5 Geolocation How-To Rating: 0 out of 5 stars0 ratingsJava Performance Optimization: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsGit Repository Management in 30 Days: Learn to manage code repositories like a pro (English Edition) Rating: 0 out of 5 stars0 ratingsData Engineering with Databricks Cookbook: Build effective data and AI solutions using Apache Spark, Databricks, and Delta Lake Rating: 0 out of 5 stars0 ratingsPrinciples of Data Science: A beginner's guide to essential math and coding skills for data fluency and machine learning Rating: 0 out of 5 stars0 ratingsMastering Time Series Analysis and Forecasting with Python Rating: 0 out of 5 stars0 ratingsComprehensive SQL Techniques: Mastering Data Analysis and Reporting Rating: 0 out of 5 stars0 ratingsMicroservices: Novice To Ninja: Build, Design And Deploy Distributed Services Rating: 0 out of 5 stars0 ratings
Internet & Web For You
No Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsTor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5Coding For Dummies Rating: 5 out of 5 stars5/5Introduction to Internet Scams and Fraud: Credit Card Theft, Work-At-Home Scams and Lottery Scams Rating: 4 out of 5 stars4/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 4 out of 5 stars4/5More Porn - Faster!: 50 Tips & Tools for Faster and More Efficient Porn Browsing Rating: 3 out of 5 stars3/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratingsSix Figure Blogging Blueprint Rating: 5 out of 5 stars5/5Web Design For Dummies Rating: 4 out of 5 stars4/5Coding with AI For Dummies Rating: 1 out of 5 stars1/5Blogging For Dummies Rating: 0 out of 5 stars0 ratingsHTML in 30 Pages Rating: 5 out of 5 stars5/5Surveillance and Surveillance Detection: A CIA Insider's Guide Rating: 3 out of 5 stars3/5Deep Dive: Exploring the Real-world Value of Open Source Intelligence Rating: 0 out of 5 stars0 ratingsHow To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5How To Make Money Blogging: How I Replaced My Day-Job With My Blog and How You Can Start A Blog Today Rating: 4 out of 5 stars4/5Cybersecurity For Dummies Rating: 5 out of 5 stars5/5
Reviews for React and React Native
0 ratings0 reviews
Book preview
React and React Native - Mikhail Sakhniuk
Preface
Over the years, React and React Native have proven themselves among JavaScript developers as popular choices for a comprehensive and practical guide to the React ecosystem. This fifth edition comes with the latest features, enhancements, and fixes of React, while also being compatible with React Native. It includes new chapters covering critical features and concepts in modern cross-platform app development with React and TypeScript.
From the basics of React to popular features such as Hooks, server rendering, and unit testing, 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. Next, you’ll learn how to improve the stability of your components using TypeScript. 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.
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.
Who this book is for
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, HTML and CSS is necessary to be able to follow along with the content covered.
What this book covers
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, Understanding React Components and Hooks, introduces the core mechanisms of components and Hooks in React application.
Chapter 4, Event Handling, the React Way, gives an overview of how events are handled by React components.
Chapter 5, Crafting Reusable Components, guides you through the process of refactoring components by example.
Chapter 6, Type Checking and Validation with TypeScript, describes the various phases that React components go through and why it’s important for React developers.
Chapter 7, Handling Navigations with Routes, provides plenty of examples of how to set up routing for your React web app.
Chapter 8, Code Splitting Using Lazy Components and Suspense, introduces code-splitting techniques that result in performant, more efficient applications.
Chapter 9, User Interface Framework Components, gives an overview of how to get started with MUI, a React component library for building UIs.
Chapter 10, High-Performance State Updates, goes into depth on the new features in React that allow for efficient state updates and a high-performing application.
Chapter 11, Fetching Data from a Server, discusses how we can retrieve the data from servers using various ways.
Chapter 12, State Management in React, covers managing state in the app with popular solutions like Redux and Mobx.
Chapter 13, Server-Side Rendering, teaches you how to use Next.js to build large-scale React applications that render content on a server and a client.
Chapter 14, Unit Testing in React, gives an overview of testing software with focus on unit testing using Vittest.
Chapter 15, Why React Native?, describes what the React Native library is and the differences between native mobile development.
Chapter 16, React Native under the Hood, gives an overview of the architecture of React Native.
Chapter 17, Kick-Starting React Native Projects, teaches you how to start a new React Native project.
Chapter 18, Building Responsive Layouts with Flexbox, describes how to create a layout and add styles.
Chapter 19, Navigating between Screens, shows the approaches to switching between screens in an app.
Chapter 20, Rendering Item Lists, describes how to implement lists of data in an application.
Chapter 21, Geolocation and Maps, explains 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, Responding to User Gestures, provides examples of how to handle user gestures.
Chapter 24, Showing Progress, shows you how to handle process indications and progress bars.
Chapter 25, Displaying Modal Screens, teaches you how to create dialog modals.
Chapter 26, Using Animations, describes how to implement animations in an app.
Chapter 27, Controlling Image Display, gives an overview of how to render images in a React Native app.
Chapter 28, Going Offline, shows how to deal with an app when a mobile phone doesn’t have an internet connection.
To get the most out of this book
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. You’ll learn how to set up a React project in Chapter 1, Why React?.
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. To work with Android simulator, you can use any kind of PC.
Download the example code files
The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/React-and-React-Native-5E. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Download the color images
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/gbp/9781805127307.
Conventions used
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: "You have the actual routes declared as
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 on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: "Select System info from the Administration panel."
Warnings or important notes appear like this.
Tips and tricks appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: Email
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
.
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
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.
Share your thoughts
Once you’ve read React and React Native, Fifth 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.
Download a free PDF copy of this book
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 below:
https://packt.link/free-ebook/9781805127307
Submit your proof of purchase.
That’s it! We’ll send your free PDF and other benefits to your email directly.
Part 1
React
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, Understanding React Components and Hooks
Chapter 4, Event Handling in the React Way
Chapter 5, Crafting Reusable Components
Chapter 6, Type-Checking and Validation with TypeScript
Chapter 7, Handling Navigations with Routes
Chapter 8, Code Splitting Using Lazy Components and Suspense
Chapter 9, User Interface Framework Components
Chapter 10, High-Performance State Updates
Chapter 11, Fetching Data from a Server
Chapter 12, State Management in React
Chapter 13, Server-Side Rendering
Chapter 14, Unit Testing in React
1
Why React?
If you’re reading this book, you probably are already familiar with React. But if you’re 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. Our goal is to learn React and React Native, but it’s also to build a scalable and adaptive architecture that can handle everything we want to build with React today and in the future. In other words, we want to create a foundation around React, with a set of additional tools and approaches that can withstand the test of time. This book will guide you through the process of using tools like routing, TypeScript typing, testing, and many more.
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. Then, we’ll touch on some of the major features of React. And finally, we will explore how we can set up a project to start to work with 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?
What’s new in React?
Setting up a new React project
What is React?
I think the one-line description of React on its home page (https://react.dev/) is concise and accurate:
A JavaScript library for building user interfaces.
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 just the view layer
React is generally thought of as the view layer in an application. Applications are typically divided into different layers, such as the view layer, the logic layer, and the data layer. React, in this context, primarily handles the view layer, which involves rendering and updating the UI based on changes in data and application state. 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:
Application logic: Start with some application logic that generates data.
Rendering data to the UI: The next step is to render this data to the UI.
React component: To accomplish this, you pass the data to a React component.
Component’s role: The React component takes on the responsibility of getting the HTML onto 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.
Simplicity is good
React doesn’t have many moving parts to learn about and understand. While React boasts a relatively simple API, it’s important to note that beneath the surface, React operates with a degree of complexity. Throughout this book, we will delve into these internal workings, exploring various aspects of React’s architecture and mechanisms to provide you with a comprehensive understanding. 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: For example, one phase of the lifecycle is when the component is about to be rendered. Within a React component, methods or hooks respond to the component’s entering and exiting phases of the React rendering process as they happen over time.
Events: These are the code that we write to respond to user interactions.
JSX: This is the syntax commonly used for describing UI structures in React components. Even though JSX is closely associated with React, it can also be used alongside other JavaScript frameworks and libraries.
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.
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 can be 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 combined, we automatically assume that this is bad and shouldn’t happen.
The syntax used by React components is called JSX (short for JavaScript XML, also known as JavaScript Syntax Extension). 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 manually perform intricate operations to change the content of a component. Instead, we describe how the UI should look in different states, and React efficiently updates the actual DOM to match. As a result, React UIs become easier and more efficient to work with, resulting in better performance.
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:
$(
document
).
ready
(
function
() { $(
'#my-button'
).
click
(
function
() { $(
'#my-paragraph'
).
addClass
(
'highlight'
); }); });
Performing these steps is easy enough. This is called imperative programming, and it’s problematic for UI development. The problem with imperative programming in UI development is that it can lead to code that is difficult to maintain and modify. This is because imperative code is often tightly coupled, meaning that changes to one part of the code can have unintended consequences elsewhere. Additionally, imperative code can be difficult to reason about, as it can be hard to understand the flow of control and the state of an application at any given time. 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 component is going to render?
export
const
App
= () => {
const
[isHighlighted, setIsHighlighted] =
useState
(
false
);
return
(
<
div
>
<
button
onClick
=
{()
=>
setIsHighlighted(true)}>Add Class
button
>
<
p
className
=
{isHighlighted
&& "
highlight
"}>
This is paragraph
p
>
div
>
); };
In this example, we’re not just writing the imperative procedure that the browser should execute. This is more like an instruction, where we say how the UI should look and what user interaction should happen on it. 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.
Data 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 data and the passage of time 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.
Performance matters
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 with 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.
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: