Book Image

Learn React with TypeScript 3

By : Carl Rippon
Book Image

Learn React with TypeScript 3

By: Carl Rippon

Overview of this book

React today is one of the most preferred choices for frontend development. Using React with TypeScript enhances development experience and offers a powerful combination to develop high performing web apps. In this book, you’ll learn how to create well structured and reusable react components that are easy to read and maintain by leveraging modern web development techniques. We will start with learning core TypeScript programming concepts before moving on to building reusable React components. You'll learn how to ensure all your components are type-safe by leveraging TypeScript's capabilities, including the latest on Project references, Tuples in rest parameters, and much more. You'll then be introduced to core features of React such as React Router, managing state with Redux and applying logic in lifecycle methods. Further on, you'll discover the latest features of React such as hooks and suspense which will enable you to create powerful function-based components. You'll get to grips with GraphQL web API using Apollo client to make your app more interactive. Finally, you'll learn how to write robust unit tests for React components using Jest. By the end of the book, you'll be well versed with all you need to develop fully featured web apps with React and TypeScript.
Table of Contents (14 chapters)

Creating reducers

A reducer is a function that is responsible for creating new state for a given action. So, the function takes in an action with the current state and returns the new state. In this section, we'll create a reducer for the two actions we have created on products.

  1. Let's start by creating a file called ProductsReducer.ts with the following import statements:
import { Reducer } from "redux";
import { IProductsState, ProductsActions, ProductsActionTypes } from "./ProductsTypes";

We are importing the Reducer type from Redux along with types for the actions and state we created earlier.

  1. Next, we need to define what the initial state is:
const initialProductState: IProductsState = {
products: [],
productsLoading: false
};

So, we are setting the products to an empty array and product loading state to false.

  1. We can now start to create...