Reader small image

You're reading from  Learn React with TypeScript - Second Edition

Product typeBook
Published inMar 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781804614204
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Carl Rippon
Carl Rippon
author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon

Right arrow

Using React Hooks

In this chapter, we will learn about React’s common Hooks and how to use them with TypeScript. We will implement the knowledge of all these Hooks in a React component that allows a user to adjust a score for a person. We will start by exploring the effect Hook and begin to understand use cases where it is useful. We will then delve into two state Hooks, useState and useReducer, understanding when it is best to use each one. After that, we will cover the ref Hook and how it differs from the state Hook, and then the memo and callback Hooks, looking at how they can help performance.

So, we’ll cover the following topics:

  • Using the effect Hook
  • Using state Hooks
  • Using the ref Hook
  • Using the memo Hook
  • Using the callback Hook

Technical requirements

We will use the following technologies in this chapter:

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

Using the effect Hook

In this section, we will learn about the effect Hook and where it is useful. We will then create a new React project and a component that makes use of the effect Hook.

Understanding the effect Hook parameters

The effect Hook is used for component side effects. A component side effect is something executed outside the scope of the component such as a web service request. The effect Hook is defined using the useEffect function from React. useEffect contains two parameters:

  • A function that executes the effect; at a minimum, this function runs each time the component is rendered
  • An optional array of dependencies that cause the effect function to rerun when changed

Here’s an example of the useEffect Hook in a component:

function SomeComponent() {
  function someEffect() {
    console.log("Some effect");
  }
  useEffect(someEffect);
  return ...
}

The preceding...

Using state Hooks

We have already learned about the useState Hook in previous chapters, but here we will look at it again and compare it against another state Hook we haven’t covered yet, useReducer. We will expand the PersonScore component we created in the last section to explore these state Hooks.

Using useState

As a reminder, the useState Hook allows state to be defined in a variable. The syntax for useState is as follows:

const [state, setState] = useState(initialState);

We will enhance the PersonScore component we created in the last section to store the person’s name in state. We will also have state for a score that is incremented, decremented, and reset using some buttons in the component. We will also add the loading state to the component, which will show a loading indicator when true.

Carry out the following steps:

  1. Open PersonScore.tsx and add useState to the React import statement:
    import { useEffect, useState } from 'react&apos...

Using the ref Hook

In this section, we will learn about the ref Hook and where it is useful. We will then walk through a common use case of the ref Hook by enhancing the PersonScore component we have been working on.

Understanding the ref Hook

The ref Hook is called useRef and it returns a variable whose value is persisted for the lifetime of a component. This means that the variable doesn’t lose its value when a component re-renders.

The value returned from the ref Hook is often referred to as a ref. The ref can be changed without causing a re-render.

Here’s the syntax for useRef:

const ref = useRef(initialValue);

An initial value can optionally be passed into useRef. The type of the ref can be explicitly defined in a generic argument for useRef:

const ref = useRef<Ref>(initialValue);

The generic argument is useful when no initial value is passed or is null. This is because TypeScript won’t be able to infer the type correctly.

...

Using the memo Hook

In this section, we will learn about the memo Hook and where it is useful. We will then walk through an example in the PersonScore component we have been working on.

Understanding the memo Hook

The memo Hook creates a memoized value and is beneficial for values that have computationally expensive calculations. The Hook is called useMemo and the syntax is as follows:

const memoizedValue = useMemo(() => expensiveCalculation(), []);

A function that returns the value to memoize is passed into useMemo as the first argument. The function in this first argument should perform the expensive calculation.

The second argument passed to useMemo is an array of dependencies. So, if the expensiveCalculation function has dependencies a and b, the call will be as follows:

const memoizedValue = useMemo(
  () => expensiveCalculation(a, b),
  [a, b]
);

When any dependencies change, the function in the first argument is executed again to...

Using the callback Hook

In this section, we will learn about the callback Hook and where it is useful. We will then use the Hook in the PersonScore component we have been working on.

Understanding the callback Hook

The callback Hook memoizes a function so that it isn’t recreated on each render. The Hook is called useCallback and the syntax is as follows:

const memoizedCallback = useCallback(() => someFunction(), []);

A function that executes the function to memoize is passed into useCallback as the first argument. The second argument passed to useCallback is an array of dependencies. So, if the someFunction function has dependencies a and b, the call will be as follows:

const memoizedCallback = useCallback(
  () => someFunction(a, b),
  [a, b]
);

When any dependencies change, the function in the first argument is executed again to return a new function to memoize. In the previous example, a new version of memoizedCallback is created...

Summary

In this chapter, we learned that all React Hooks must be called at the top level of a function component and can’t be called conditionally.

The useEffect Hook can be used to execute component side effects when it is rendered. We learned how to use useEffect to fetch data, which is a common use case.

useReducer is an alternative to useState for using state, and we experienced using both approaches in our PersonScore example component. useState is excellent for primitive state values. useReducer is great for complex object state values, particularly when state changes depend on previous state values.

The useRef Hook creates a mutatable value and doesn’t cause a re-render when changed. We used useRef to set focus to an HTML element after it was rendered, which is a common use case.

The useMemo and useCallback Hooks can be used to memoize values and functions, respectively, and can be used for performance optimization. The examples we used for these Hooks...

Questions

Answer the following questions to check what you have learned about React Hooks:

  1. The following component renders some text for 5 seconds. This is problematic though – what is the problem?
    export function TextVanish({ text }: Props) {
      if (!text) {
        return null;
      }
      const [textToRender, setTextToRender] = useState(text);
      useEffect(() => {
        setTimeout(() => setTextToRender(""), 5000);
      }, []);
      return <span>{textToRender}</span>;
    }
  2. The following code is a snippet from a React component that fetches some data and stores it in state. There are several problems with this code though – can you spot any of the problems?
    const [data, setData] = useState([]);
    useEffect(async () => {
      const data = await getData();
      setData(data);
    });
  3. How many times will the following component re-render in production mode...

Answers

  1. The problem with the component is that both useState and useEffect are called conditionally (when the text prop is defined), and React doesn’t allow its Hooks to be called conditionally. Placing the Hooks before the if statement resolves the problem:
    export function TextVanish({ text }: Props) {
      const [textToRender, setTextToRender] = useState(text);
      useEffect(() => {
        setTimeout(() => setTextToRender(""), 5000);
      }, []);
      if (!text) {
        return null;
      }
      return <span>{textToRender}</span>;
    }
  2. The main problem with the code is that the effect function can’t be marked as asynchronous with the async keyword. A solution is to revert to the older promise syntax:
    const [data, setData] = useState([]);
    useEffect(() => {
      getData().then((theData) => setData(theData));
    });

The other major problem is that no dependencies...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React with TypeScript - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781804614204
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
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon