Learn React with TypeScript - Carl Rippon - E-Book

Learn React with TypeScript E-Book

Carl Rippon

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Reading, navigating, and debugging a large frontend codebase can be challenging. Learn React with TypeScript, 3rd Edition helps you overcome these challenges by teaching you React, TypeScript, and Next.js, which are core technologies for building scalable, high-performance apps.
Updated for React 19, this new edition covers new features such as React Server Components, server functions, and powerful modern hooks, including useFormStatus and useActionState. You'll build type-safe components using TypeScript, making this book ideal for React beginners who want to master patterns aligned with real-world frontend and React developer roles.
You’ll also explore Next.js for RSCs and routing, and learn to use Zustand for global state in React—a lightweight alternative to traditional state managers. The chapters guide you through efficient data-fetching strategies with RSCs in Next.js, as well as in single-page applications (SPAs). The book also covers form handling, reusable architecture, and testing React components with Vitest to ensure robust, production-ready apps.
By the end of this book, you’ll have the confidence and skills to build maintainable React applications with TypeScript and Next.js, following modern web development best practices.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 437

Veröffentlichungsjahr: 2025

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Learn React with TypeScript

Third Edition

A beginner's guide to building real-world, production-ready web apps with React 19 and TypeScript

Carl Rippon

Learn React with TypeScript

Third Edition

Copyright © 2025 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 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.

Portfolio Director: Ashwin Nair

Relationship Lead: Bhavya Rao

Project Manager: Aparna Nair

Content Engineer: Adrija Mitra

Technical Editor: Sweety Pagaria

Copy Editor: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Shantanu Zagade

Growth Lead: Priyadarshini Sharma

First published: November 2018

Second edition: March 2023

Third edition: June 2025

Production reference: 1050625

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83664-317-3

www.packt.com

Contributors

About the author

Carl Rippon is a seasoned software developer with over 25 years of experience in building complex business applications across a range of industries. For the past 15 years, he has specialized in modern JavaScript technologies – particularly React, TypeScript, and Next.js. A passionate educator and writer, Carl has authored more than 100 blog posts, sharing practical insights and solutions with the developer community.

I’d like to thank Sarah, Ellie-Jayne, Lily-Rose, Fudge, and Arlo for all the support and encouragement they’ve given me while writing this book. A special thanks to everyone on the Packt editorial team for their hard work and great feedback, especially Adrija Mitra.

About the reviewers

Gurjit Singh is a Berlin-based senior frontend engineer at Storyblok, with over six years of experience in building modern web applications using React, TypeScript, and Node.js. Formerly employed at zendesk.com, he contributed at an organizational level across AI-powered and customer-facing initiatives. Gurjit is also an active open source contributor. His work has led to collaborations with engineers at Apple, Wix, and more, and he was invited to a hackathon in San Francisco, US, for his contributions to the Khalis Foundation. He enjoys speaking at conferences and sharing practical engineering insights with the developer community. In his free time, he’s passionate about Indian classical music, reading psychology books, and traveling the globe.

Andrew Baisden is an experienced software developer skilled in the JavaScript and Python ecosystems. He builds cross-platform applications using frontend technologies such as React, TypeScript, and modern frameworks. Experienced with backend and mobile development, Andrew is also passionate about sharing knowledge and writes technical articles for various publications. He also engages with his social media audience by offering valuable resources and content. Andrew combines education with constant self-improvement to stay current with technology.

The author acknowledges the use of cutting-edge AI, in this case ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It's important to note that the content itself has been crafted by the author and edited by a professional publishing team.

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/GxSkC

Table of Contents

Preface

Part 1: Introduction

1

Getting Started with React

Technical requirements

Understanding the benefits of React

Creating a React project

Understanding the project

Adding linting to Visual Studio Code

Adding code formatting

Starting the app in development mode

Producing a production build

Understanding the structure of a React app

Understanding the React entry point

Understanding the React component tree

Understanding a React component

Creating a component

Creating a basic Alert component

Adding Alert to the App component

Using props

Understanding props

Adding props to the Alert component

Using state

Understanding state

Implementing a visible state in the Alert component

Adding a close button to Alert

Using events

Understanding events

Implementing a close button click handler in the alert

Implementing an alert close event

Using React developer tools

Using the Components tool

Using the Profiler tool

Summary

Questions

Answers

2

Getting Started with TypeScript

Technical requirements

Understanding the benefits of TypeScript

Understanding TypeScript

Catching type errors early

Improving developer experience and productivity with IntelliSense

Understanding JavaScript types

Using basic TypeScript types

Using type annotations

Using type inference

Using the Date type

Using the any type

Using the unknown type

Using arrays

Creating TypeScript types

Using object types

Creating type aliases

Creating union types

Using the TypeScript compiler

Creating a React and TypeScript component

Creating a project

Adding a props type

Adding a state type

Summary

Questions

Answers

3

Using React Hooks

Technical requirements

Using the effect Hook

Understanding the effect Hook parameters

The rules of Hooks

Effect cleanup

Creating the project

Fetching data using the effect Hook

Using state Hooks

Using useState

Understanding useReducer

Using useReducer

Using the ref Hook

Understanding the ref Hook

Using the ref Hook

Using the memo Hook

Understanding the memo Hook

Using the memo Hook

Using the callback Hook

Understanding the callback Hook

Understanding when a component is re-rendered

Using the callback Hook

Other React Hooks

useId

useTransition

useDeferredValue

Hooks covered in other chapters

Summary

Questions

Answers

Part 2: App Fundamentals

4

Approaches to Styling React Frontends

Technical requirements

Using plain CSS

Creating the project

Understanding how to reference CSS

Using plain CSS in the alert component

Experiencing CSS clashes

Using CSS modules

Understanding CSS modules

Using CSS modules in the alert component

Using Tailwind CSS

Understanding Tailwind CSS

Installing and configuring Tailwind CSS

Using Tailwind CSS

Using SVGs

Understanding how to use SVGs in React

Adding SVGs to the alert component

Other styling approaches

Using inline styles

Using SCSS

Using CSS-in-JS

Summary

Questions

Answers

5

Using React Server and Client Components

Technical requirements

Understanding SPAs

Understanding the SPA problem

Understanding the benefits of SPAs

Understanding Server Components

Understanding what a Server Component is

Understanding how RSCs address the SPA problem

Understanding the benefits of Server Components

Creating Server Components

Creating the project

Creating an RSC

Understanding how Server Components work

Exploring Client Components

Understanding Client Components

Understanding Client Component rendering

Specifying Client Components

Creating Client Components

Composing Server and Client Components

RSCs versus Client Components

Understanding when to use an RSC or Client Component

Understanding client boundaries

Rendering an RSC in ColorModeToggle

Summary

Further reading

Questions

Answers

6

Creating a Multi-Page App with Next.js

Technical requirements

Creating routes

Creating the project

Understanding routes

Creating a posts route

Creating navigation

Using the Link component

Using useRouter

Creating shared layout

Understanding layout components

Creating a header

Creating dynamic routes

Understanding dynamic routes

Creating a blog post dynamic route

Using search parameters

Understanding search parameters

Adding search functionality to the app

Summary

Questions

Answers

Part 3:Data

7

Server Component Data Fetching and Server Function Mutations

Technical requirements

Understanding server-side and client-side data fetching

Client-side data fetching

Server-side data fetching

Understanding the benefits

Getting set up

Creating the project

Setting up the database

Fetching data using an RSC

Implementing query functions

Calling query functions from RSCs

Adding type safety to a database query

Adding loading indicators using React Suspense

Understanding the need for loading indicators

Adding a delay

Understanding React Suspense

Implementing loading indicators

Handling errors with React error boundaries

Understanding React error boundaries

Implementing error boundaries

Mutating data using a Server Function

Understanding a Server Function

Creating a Server Function

Adding a progress indicator

Handling errors

Summary

Questions

Answers

8

Client Component Data Fetching and Mutations with TanStack Query

Technical requirements

Fetching data using TanStack Query

Understanding the challenges with useEffect for data fetching

Understanding TanStack Query

Setting up the project

Fetching blog post data

Using a Route Handler with TanStack Query

Understanding the benefits of Route Handlers

Using Route Handlers

Adding type safety to the API response

Mutating data using a TanStack Query mutation

Understanding TanStack Query mutations

Using useMutation

Summary

Questions

Answers

9

Working with Forms

Technical requirements

Using basic forms

Creating the project

Creating a native form

Using a Route Handler for submission

Creating a database mutation

Creating a Route Handler

Integrating the form submission with the Route Handler

Using a Server Action for submission

Understanding Server Actions

Using a Server Action in ContactForm

Adding server validation

Using useFormStatus

Understanding useFormStatus

Using useFormStatus

Using useActionState

Understanding useActionState

Using useActionState

Returning state from the Server Action

Adding action state to the form

Adding field errors

Using React Hook Form

Understanding React Hook Form

Understanding client-side validation

Understanding the useForm Hook

Understanding the register function

Specifying validation

Obtaining validation errors

Handling submission

Using React Hook Form

Implementing optimistic updates

Understanding useOptimistic

Using useOptimistic

Adding an unoptimistic contacts page

Making done optimistic

Summary

Questions

Answers

Part 4:Advanced React

10

State Management

Technical requirements

Understanding the types of state

Server state

Form state

URL state

Local state

Derived state

Shared state

Using prop drilling

Creating the project

Understanding and using prop drilling

Using better composition

Using React context

Understanding React context

Using React context

Using Zustand

Understanding Zustand

Using Zustand

Using TanStack Query and URL parameters

Using TanStack Query

Using URL parameters

Summary

Questions

Answers

11

Reusable Components

Technical requirements

Creating the project

Using generic props

Understanding generics

Generic functions

Generic types

The keyof operator

Generic React components

Creating a basic list component

Using prop spreading

Using render props

Understanding the render props pattern

Adding a renderItem prop

Adding checked functionality

Creating custom hooks

Understanding custom hooks

Extracting checked logic into a custom hook

Allowing the internal state to be controlled

Understanding how the internal state can be controlled

Allowing checkedIds to be controlled

Summary

Questions

Answers

12

Unit Testing with Vitest and the React Testing Library

Technical requirements

Testing pure functions

Understanding a test

Testing isChecked

Testing exceptions

Running tests

Testing components

Understanding the React Testing Library

A basic component test

Understanding queries

Implementing checklist component tests

Using test IDs

Simulating user interactions

Understanding fireEvent and user-event

Implementing checklist tests for checking items

Getting code coverage

Installing the code coverage tool

Running code coverage

Understanding the code coverage report

Gaining full coverage on the checklist component

Ignoring files in the coverage report

Summary

Questions

Answers

Other Books You May Enjoy

Index

Preface

React was built by Meta to provide more structure to its code base and allow it to scale much better. React worked so well for Facebook that they eventually made it open source. Today, React is the dominant technology for building frontends; it allows us to build small, isolated, and highly reusable components that can be composed together to create complex frontends. With advancements such as React Server Components, React has further expanded its capabilities, enabling developers to seamlessly combine server-side rendering and client-side interactivity for highly optimized and dynamic applications.

TypeScript was built by Microsoft to help developers more easily develop large JavaScript-based programs. It is a superset of JavaScript that brings a rich type system to it. This type system helps developers catch bugs early and allows tools to be created to navigate and refactor code robustly.

This book will teach you how to use both of these technologies to create large, sophisticated frontends that are easy to maintain, while also exploring modern features such as React Server Components to enhance performance and productivity.

Who this book is for

If you are a developer who wants to create large and complex frontends with React and TypeScript, this book is for you. The book doesn’t assume you have any previous knowledge of React or TypeScript – however, basic knowledge of JavaScript, HTML, and CSS will help you get to grips with the concepts covered.

What this book covers

Chapter 1, Getting Started with React, covers creating React projects and the fundamentals of building React components. This includes making a component configurable using props and interactive using state.

Chapter 2, Getting Started with TypeScript, starts with the fundamentals of TypeScript and its type system. This includes using inbuilt types as well as creating new types. The chapter then covers creating a React component with TypeScript types.

Chapter 3, Using React Hooks, details the common React Hooks and their typical use cases. The chapter also covers how to use the Hooks with TypeScript to make them type-safe.

Chapter 4, Approaches to Styling React Frontends, walks through how to style React components using several different approaches. The benefits of each approach are also explored.

Chapter 5, Using React Server and Client Components, covers how and when to use React Server Components and Client Components and also how to compose them together.

Chapter 6, Creating a Multi-Page App with Next.js, covers the fundamentals of building multi-page apps in a popular React framework called Next.js. This includes implementing different pages, links between them, and page parameters.

Chapter 7, Server Component Data Fetching and Server Function Mutations, demonstrates how React Server Components can fetch data from a database. The chapter also includes mutating database data using a React Server Function.

Chapter 8, Client Component Data Fetching and Mutations with TanStack Query, covers how React Client Components can fetch and mutate data from a database using a popular library called TanStack Query.

Chapter 9, Working with Forms, explores how forms can be implemented using several different approaches, including the latest React Hooks and a popular forms library.

Chapter 10, State Management, walks through how React state can be shared between different components. Several approaches are explored along with their benefits.

Chapter 11, Reusable Components, brings in several patterns for making React components highly reusable but still type-safe.

Chapter 12, Unit Testing with Vitest and the React Testing Library, first delves into how functions can be tested with Vitest. The chapter then moves on to how React components can be tested with the help of the React Testing Library.

To get the most out of this book

To follow along with this book, you’ll need to have the following technologies installed on your Windows or macOS computer:

A modern browser, such as Google Chrome, which you can download from https://www.google.com/chromeNode.js and npm, available at https://nodejs.org/en/downloadVisual Studio Code, downloadable from https://code.visualstudio.com

Software/hardware covered in the book

React 19 or later

Next.js 15 or later

TypeScript 5 or later

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.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Learn-React-with-TypeScript-Third-Edition/tree/main/. 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!

Conventions used

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: “We used the Form component from Next.js to optimize the form submission performance.”

A block of code is set as follows:

export default function Home() { return ( <main> </main> ); }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

import Form from ‘next/form’; export function ContactForm() { return ( <Form ... > ... </Form> ); }

Any command-line input or output is written as follows:

npm run dev

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: “In the running app, try clicking the Done button to mark an item as done.”

Tips or important notes

Appear like this.

Get in touch

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.

Share Your Thoughts

Once you’ve read Learn React with TypeScript, Third 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/9781836643173

Submit your proof of purchase.That’s it! We’ll send your free PDF and other benefits to your email directly.

Part 1: Introduction

This part will get you started with both React and TypeScript, learning how to create a new project and implement interactive type-safe components. We will also learn about React’s common Hooks in detail and the cases in which they are used in applications.

This part has the following chapters:

Chapter 1, Getting Started with ReactChapter 2, Getting Started with TypeScriptChapter 3, Using React Hooks