Reader small image

You're reading from  React 18 Design Patterns and Best Practices - Fourth Edition

Product typeBook
Published inJul 2023
Reading LevelExpert
PublisherPackt
ISBN-139781803233109
Edition4th Edition
Languages
Tools
Right arrow
Author (1)
Carlos Santana Roldán
Carlos Santana Roldán
author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán

Right arrow

React Hooks

React Hooks have revolutionized the way we write React applications, allowing us to use functional components instead of class components, and making coding faster and more efficient. Since their introduction in React 16.8, Hooks have become an essential part of React development and have greatly improved the performance of our applications. With Hooks, we can manage the state, handle side effects, and reuse code in a more concise and readable way. In the next chapter, we will explore the different types of Hooks and how to use them to enhance our React applications.

In this chapter, we will cover the following topics:

  • The new React Hooks and how to use them
  • The rules of the Hooks
  • How to migrate a class component to React Hooks
  • Understanding the component life cycle with Hooks and effects
  • How to fetch data with Hooks
  • How to memoize components, values, and functions with memo, useMemo, and useCallback
  • How to implement...

Technical requirements

To complete this chapter, you will require the following:

  • Node.js 19+
  • Visual Studio Code

You can find the code for this chapter in the book’s GitHub repository at https://github.com/PacktPublishing/React-18-Design-Patterns-and-Best-Practices-Fourth-Edition/tree/main/Chapter08.

Introducing React Hooks

React Hooks are a new addition to React 16.8. They let you use state and other React features without writing a React class component. React Hooks are also backward-compatible, which means they do not contain any breaking changes or not replace your knowledge of React concepts. Over the course of this chapter, we will see an overview of Hooks for experienced React users, and we are also going to learn about some of the most common React Hooks such as useState, useEffect, useMemo, useCallback, and memo.

No breaking changes

In the context of React development, it’s a common misconception that the introduction of React Hooks has made class components obsolete. However, this is not true, as there are no plans to remove classes from React. The Hooks API does not replace your understanding of React concepts, but rather offers a more streamlined approach to working with those concepts, such as props, states, context, refs, and life cycles, which you...

Rules of Hooks

React Hooks are basically JavaScript functions, but there are two rules that you need to follow in order to use them. React provides a linter plugin to enforce those rules for you, which you can install by running the following command:

npm install --save-dev eslint-plugin-react-hooks

Let’s look at these two rules.

Rule 1: Only call Hooks at the top level

To ensure the proper functioning of React Hooks, it is important to avoid calling them inside loops, conditions, or nested functions. Instead, it is recommended to always use Hooks at the top level of your React function. This practice ensures that Hooks are called in the same order every time a component is rendered, allowing React to correctly preserve the state of Hooks between multiple useState and useEffect calls. Following this rule will help you write more efficient and maintainable code with React Hooks.

Rule 2: Only call Hooks from React functions

To ensure that all stateful...

Migrating a class component to React Hooks

Let’s transform code that is currently using class components and is also using some life cycle methods. In this example, we are fetching the issues from a GitHub repository and listing them.

For this example, you will need to install axios to perform the fetch:

npm install axios

This is the class component version:

import axios from 'axios'
import { Component } from 'react'
type Issue = {
  number: number
  title: string
  state: string
}
type Props = {}
type State = { issues: Issue[] }
class Issues extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = {
      issues: []
    }
  }
  componentDidMount() {
    axios.get('https://api.github.com/repos/ContentPI/ContentPI/issues')
      .then((response: any) => {
        this.setState({
          issues: response.data
        })
      })
  }
  render() {
    const { issues = [] } = this...

Understanding React effects

In this section, we will learn the difference between the component life cycle methods that we used in class components and the new React effects. Even if you have read in other places that they are the same, just with a different syntax, this is not correct.

Understanding useEffect

When you work with useEffect, you need to think in terms of effects. If you want to perform the equivalent method of componentDidMount using useEffect, you can do the following:

useEffect(() => {
  // Here you perform your side effect
}, [])

The first parameter is the callback of the effect that you want to execute, and the second parameter is the dependencies array. If you pass an empty array ([]) to the dependencies, the state and props will have their original initial values.

However, it is important to mention that even though this is the closest equivalent to componentDidMount, it does not have the same behavior. Unlike componentDidMount and componentDidUpdate...

Understanding the useReducer Hook

You probably have some experience using Redux (react-redux) with class components, and if that is the case, then you will understand how useReducer works. The concepts are basically the same: actions, reducers, dispatch, store, and state. Even if, in general, it seems very similar to react-redux, they have some differences. The main difference is that react-redux provides middleware and wrappers such as thunk, sagas, and many more besides, while useReducer just gives you a dispatch method that you can use to dispatch plain objects as actions. Also, useReducer does not have a store by default; instead, you can create one using useContext, but this is just reinventing the wheel.

Let’s create a basic application to understand how useReducer works. You can start by creating a new React app:

npx create-vite reducer --template react-ts

Then, as always, you can delete all files in your src folder except App.tsx and index.tsx to start...

Summary

I hope you enjoyed reading this chapter, which is full of very good information pertaining to the new React Hooks. So far, you have learned how the new React Hooks work; how to fetch data with Hooks; how to migrate a class component to React Hooks; how the effects work, the difference between memo, useMemo, and useCallback; and finally, you learned how the useReducer Hook works and the main difference compared with react-redux. This will help you to improve the performance of your React components.

In the next chapter, we will learn about React Router v6 and how to implement it in our projects.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React 18 Design Patterns and Best Practices - Fourth Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781803233109
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán