Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learn React with TypeScript
Learn React with TypeScript

Learn React with TypeScript: A beginner's guide to reactive web development with React 19 and TypeScript , Third Edition

Arrow left icon
Profile Icon Carl Rippon
Arrow right icon
Coming Soon Coming Soon Publishing in Jul 2025
€18.99 per month
eBook Jul 2025 3rd Edition
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Carl Rippon
Arrow right icon
Coming Soon Coming Soon Publishing in Jul 2025
€18.99 per month
eBook Jul 2025 3rd Edition
Subscription
Free Trial
Renews at €18.99p/m
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Info icon
You can access this book only when it is published in Jul 2025
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learn React with TypeScript

Getting Started with React

Facebook has become an incredibly popular app. As its popularity has grown, so has the demand for new features. React is Meta’s answer to helping more people work on the Facebook code base and deliver features more quickly. React has worked so well for Facebook that Meta eventually made it open source. Today, React is a mature library for building component-based frontends that is extremely popular and has a massive community and ecosystem. 

TypeScript is also a popular, mature library maintained by another big company, Microsoft. It allows users to add a rich type system to their JavaScript code, helping them be more productive, particularly in large code bases. 

This book will teach you how to use these awesome libraries to build robust frontends that are easy to maintain. The first two chapters in the book will introduce React and TypeScript separately. You’ll then learn how to use React and TypeScript...

Technical requirements

We use the following tools in this chapter: 

  • Browser: A modern browser such as Google Chrome.
  • Terminal: We will use a terminal to execute commands to create a React project. The default terminal available in your operating system will work fine.
  • Visual Studio Code: We need a code editor to create our first React component. Visual Studio Code is a popular editor that we’ll use throughout this book. This can be downloaded and installed from https://code.visualstudio.com.
  • Node.js and npm: Node.js will be required to build our React app and run it on a development server. npm is a package manager that allows us to easily install libraries into our app. These tools come together and can be downloaded and installed from https://nodejs.org/en/download.

All the code snippets in this chapter can be found online at https://github.com/PacktPublishing/Learn-React-with-TypeScript-Third-Edition/tree/main/Chapter01

Understanding the benefits of React

Before we start creating our first React component, in this section, we will understand what React is and explore some of its benefits.

React is an incredibly popular frontend library. We have already mentioned that Meta uses React for Facebook, but many other famous companies use it too, such as Netflix, Uber, and Airbnb. React’s popularity has resulted in a huge ecosystem surrounding it that includes great tools, popular libraries, and many experienced developers.

One reason for React’s popularity is that it is simple. This is because it focuses on doing one thing very well – providing a powerful mechanism for building UI components. Components are pieces of the UI that can be composed together to create a frontend. Furthermore, components can be reusable so that they can be used on different screens or even in other apps.

React’s narrow focus means it can be incorporated into an existing app, even if it uses...

Creating a React project

In this section, we will create a React project and configure Visual Studio Code to work optimally with it. We will also cover how to run a React app in development mode and also how to produce a production build.

We will create a React project using Vite, a popular build tool and development server for React apps. Carry out the following steps:

  1. In a terminal, in a folder of your choice, execute the following command to instruct Vite to create a project:
    npm create vite@latest
  2. A prompt for the project name appears. The project name will be the folder name containing the project code. So, enter a name of your choice and press Enter.
Figure 1.1 – Creating a Vite project

Figure 1.1 – Creating a Vite project

  1. A prompt now appears for the framework for the project. Select React by using the down arrow key to move to React and press Enter.

Figure 1.2 – Selecting the React framework

  1. Lastly, the variant...

Understanding the structure of a React app

In this section, we will explore the entry point of the React app created in the last section and how it is loaded into the HTML page. We will then learn about the React component tree and how a component is defined.

Understanding the React entry point

The entry point of this React app is in the main.jsx file in the src folder. Open this file and inspect its contents. It contains a call to React’s createRoot function as follows:

createRoot(document.getElementById(‘root’)).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

Here’s an explanation of this code:

  • As the name suggests, createRoot creates a root in the HTML document for the React components. createRoot takes in a DOM element for where to place the React components, which is the element that has the ID of ‘root’ in this case.
  • createRoot returns an object containing...

Creating a component

In this section, we will create a React component and reference this within the App component.

Creating a basic Alert component

We are going to create a component that displays an alert, which we will simply call Alert. It will consist of an icon, a heading, and a message.

Note

A React component name must start with a capital letter. If a component name starts with a lowercase letter, it is treated as a DOM element and won’t render properly.

Carry out the following steps to create the component in the project:

  1. Create a new file in the src folder called Alert.jsx.

Note

The filename for component files isn’t important to React or the React transpiler. It is common practice to use the same name as the component, either in Pascal or snake case. However, the file extension must be .js or .jsx for React transpilers to recognize these as React components.

  1. Open the Alert.jsx file and enter the following code in it...

Using props

Currently, the Alert component is pretty inflexible. For example, the alert consumer can’t change the heading or the message. At the moment, the heading or the message needs to be changed within Alert itself. Props solve this problem, and we will learn about them in this section.

Note

Props is short for properties. The React community often refers to these as props, so we will do so in this book.

Understanding props

The props parameter is an optional parameter that is passed into a React component. This parameter is an object containing the properties of our choice, allowing a parent component to pass data. The following code snippet shows a props parameter in a ContactDetails component:

function ContactDetails(props) {
  console.log(props.name);
  console.log(props.email);
  ...
}

The props parameter contains the name and email properties in the preceding code snippet.

Note

The parameter doesn’t have to...

Using state

React component state is a special variable that may change over the lifecycle of a component. In this section, we’ll learn about the state variable and use it within our Alert component. We will use state to allow the alert to be closed by the user.

Understanding state

There isn’t a predefined list of states; we define what’s appropriate for a given component. Some components won’t even need any state – the Alert component hasn’t required a state for the requirements so far.

The state is a key part of making a component interactive. When a user interacts with a component, the component’s output may need to change. A change to the state causes the component to refresh, more often referred to as re-render.

The state is defined using a useState function from React. The useState function is one of React’s Hooks. There is a whole chapter on React Hooks in Chapter 3, Using React Hooks.

The syntax for useState...

Using events

Events are another key part of allowing a component to be interactive. In this section, we will understand what React events are and how to use events on DOM elements. We will also learn how to create our own React events.

We will continue to expand the Alert component’s functionality as we learn about events. We will start by finishing the close button implementation before creating an event for when the alert has been closed.

Understanding events

Browser events happen as the user interacts with DOM elements. For example, clicking a button raises a click event from that button.

Logic can be executed when an event is raised. For example, an alert can be closed when its close button is clicked. A function called an event handler (sometimes referred to as an event listener) can be registered on an element for an event that contains the logic to execute when that particular event happens.

Note

See the following link for more information on browser...

Using React developer tools

React developer tools is a browser extension available for Chrome, Firefox, and Edge. The tools allow React apps to be inspected and debugged. In this section, we are going to install and use these tools on the Alert component we have implemented in this chapter.

The links to the extensions are as follows:

Follow the instructions in the relevant link to install the extension in your browser. You may need to reopen the browser for the tools to be available.

Using the Components tool

The first tool we are going to explore is the Components tool. It allows you to inspect the current props and state of a component. Carry out the following steps...

Summary

We now understand that React is a popular library for creating component-based frontends. In this chapter, we created an Alert component using React.

Component output is declared using a mix of HTML and JavaScript called JSX. JSX needs to be transpiled into JavaScript before it can be executed in a browser.

Props can be passed into a component as JSX attributes. This allows consumers of the component to control its output and behavior. A component receives props as an object parameter. The JSX attribute names form the object parameter property names. We implemented a range of props in this chapter in the Alert component.

Events can be handled to execute logic when the user interacts with the component. We created an event handler for the close button click event in the Alert component.

State can be used to re-render a component and update its output. The state is defined using the useState Hook and is often updated in event handlers. We created a state for whether...

Questions

Answer the following questions to reinforce what you have learned in this chapter:

  1. What is wrong with the following component definition?
    export function important() {
      return <div>This is really important!</div>;
    }
  2. Component props are passed into a component as follows:
    <ContactDetails name=”Fred” email=”[email protected]” />

    The component is then defined as follows:

    export function ContactDetails({ firstName, email }) {
      return (
        <div>
          <div>{firstName}</div>
          <div>{email}</div>
        </div>
      );
    }

    The name Fred isn’t output though. What is the problem?

  3. What is the initial value of the loading state defined here?
    const [loading, setLoading] = useState(true);
  4. What is wrong with how the state is set in the following component?
    export...

Answers

Here are the answers to the preceding questions:

  1. The problem with the component definition is that its name is in lowercase. React functions must be named with an uppercase first character:
    export function Important() {
      ...
    }
  2. The problem is that a name prop is passed rather than firstName. Here’s the corrected JSX:
    <ContactDetails firstName=”Fred” email=”[email protected]” />
  3. The initial value of the loading state is true.
  4. The state isn’t updated using the state setter function. Here’s the corrected version of the state being set:
    export function Agree() {
      const [agree, setAgree] = useState();
      return (
        <button onClick={() => setAgree(true)}>
          Click to agree
        </button>
      );
    }
  5. The problem is that clicking the button will cause an error if onAgree isn’t passed...

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

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

Left arrow icon Right arrow icon

Key benefits

  • Explore React server components and server actions to unlock powerful performance gains
  • Master the ins and outs of React forms, leveraging new hooks for even greater control
  • Uncover the secrets to crafting highly reusable components with proven design patterns
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Reading, navigating, and debugging a large frontend codebase can feel overwhelming for web developers, but you can overcome this with expert guidance from a seasoned software professional with over 20 years’ experience in developing a complex line of business applications. This book will help you learn React, TypeScript, and Next.js—the core technology stack behind scalable, high-performance web applications used by top companies. This third edition of Learn React with TypeScript is updated with the latest features of React 19, including server components, server actions, and powerful new hooks. The chapters show you how to use TypeScript’s advanced features for enhanced code reliability and maintainability when building robust, type-safe components. You’ll explore efficient data fetching strategies with RSCs in Next.js, as well as in single-page applications (SPAs). The book also covers modern state management with Zustand, best practices for form handling, and strategies for building well-structured, reusable components that streamline development. Finally, you’ll focus on unit testing with Vitest, ensuring your React components are resilient and error-free. By the end of this book, you'll have at your disposal the skills and best practices needed to create maintainable and performant React applications with TypeScript and Next.js.

Who is this book for?

This book is for experienced frontend developers looking to build large-scale web applications using React and TypeScript. Intermediate knowledge of JavaScript, HTML, and CSS is a prerequisite.

What you will learn

  • Apply effective styling techniques to design stunning and visually engaging frontends
  • Leverage server components to seamlessly integrate with client components for optimized performance
  • Fetch and manage backend data efficiently to deliver a smooth and responsive user experience
  • Develop high-performance, interactive forms using server actions
  • Implement Zustand for efficient state-sharing across components
  • Build scalable, multi-page applications effortlessly with Next.js
  • Write robust unit tests using Vitest and React Testing Library for React components

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 08, 2025
Edition : 3rd
Language : English
ISBN-13 : 9781836643166
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Info icon
You can access this book only when it is published in Jul 2025
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 08, 2025
Edition : 3rd
Language : English
ISBN-13 : 9781836643166
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Table of Contents

19 Chapters
Part 1: Introduction Chevron down icon Chevron up icon
Chapter 1: Getting Started with React Chevron down icon Chevron up icon
Chapter 2: Getting Started with TypeScript Chevron down icon Chevron up icon
Chapter 3: Using React Hooks Chevron down icon Chevron up icon
Part 2: App Fundamentals Chevron down icon Chevron up icon
Chapter 4: Approaches to Styling React Frontends Chevron down icon Chevron up icon
Chapter 5: Using React Server and Client Components Chevron down icon Chevron up icon
Chapter 6: Creating a Multi-Page App with Next.js Chevron down icon Chevron up icon
Part 3: Data Chevron down icon Chevron up icon
Chapter 7: Server Component Data Fetching and Server Function Mutations Chevron down icon Chevron up icon
Chapter 8: Client Component Data Fetching and Mutations with TanStack Query Chevron down icon Chevron up icon
Chapter 9: Working with Forms Chevron down icon Chevron up icon
Part 4:Advanced React Chevron down icon Chevron up icon
Chapter 10: State Management Chevron down icon Chevron up icon
Chapter 11: Reusable Components Chevron down icon Chevron up icon
Chapter 12: Unit Testing with Vitest and the React Testing Library Chevron down icon Chevron up icon
Chapter 13: Unlock Your Book’s Exclusive Benefits Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.