Book Image

React 18 Design Patterns and Best Practices - Fourth Edition

By : Carlos Santana Roldán
4.2 (6)
Book Image

React 18 Design Patterns and Best Practices - Fourth Edition

4.2 (6)
By: Carlos Santana Roldán

Overview of this book

React helps you work smarter, not harder — but to reap the benefits of this popular JavaScript library and its components, you need a straightforward guide that will teach you how to make the most of it. React 18 Design Patterns and Best Practices will help you use React effectively to make your applications more flexible, easier to maintain, and improve their performance, while giving your workflow a huge boost. With a better organization of topics and knowledge about best practices added to your developer toolbox, the updated fourth edition ensures an enhanced learning experience. The book is split into three parts; the first will teach you the fundamentals of React patterns, the second will dive into how React works, and the third will focus on real-world applications. All the code samples are updated to the latest version of React and you’ll also find plenty of new additions that explore React 18 and Node 19’s newest features, alongside MonoRepo Architecture and a dedicated chapter on TypeScript. By the end of this book, you'll be able to efficiently build and deploy real-world React web applications.
Table of Contents (20 chapters)
18
Other Books You May Enjoy
19
Index

Types

In the last example, we saw how to specify some primitive types for our function parameter and returned value, but you’re probably wondering how you can describe an object or array with more details. Types can help us to describe our objects or arrays in a better way. For example, let’s suppose you want to describe a User type to save the information into the database:

type User = {
  username: string
  email: string
  name: string
  age: number
  website: string
  active: boolean
}
const user: User = {
  username: 'czantany',
  email: '[email protected]',
  name: 'Carlos Santana',
  age: 33,
  website: 'http://www.js.education',
  active: true
}
// Let's suppose you will insert this data using Sequelize...
models.User.create({ ...user }}

We get the following error if we forget to add one of the nodes or put an invalid value in one of them:

Text  Description automatically generated

Figure 2.2: Age is missing in type User but is required

If you need optional nodes, you can always put a ? next to the age of the node, as shown in the following code block:

type User = {
  username: string
  email: string
  name: string
  age?: number
  website: string
  active: boolean
}

You can name type as you want, but a good practice to follow is to add a prefix of T. For example, the User type will become TUser. In this way, you can quickly recognize that it is type and you don’t get confused thinking it is a class or a React component.