Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
React Key Concepts

You're reading from  React Key Concepts

Product type Book
Published in Dec 2022
Publisher Packt
ISBN-13 9781803234502
Pages 590 pages
Edition 1st Edition
Languages
Author (1):
Maximilian Schwarzmüller Maximilian Schwarzmüller
Profile icon Maximilian Schwarzmüller

Table of Contents (16) Chapters

Preface
1. React – What and Why 2. Understanding React Components and JSX 3. Components and Props 4. Working with Events and State 5. Rendering Lists and Conditional Content 6. Styling React Apps 7. Portals and Refs 8. Handling Side Effects 9. Behind the Scenes of React and Optimization Opportunities 10. Working with Complex State 11. Building Custom React Hooks 12. Multipage Apps with React Router 13. Managing Data with React Router 14. Next Steps and Further Resources Appendix

8. Handling Side Effects

Learning Objectives

By the end of this chapter, you will be able to do the following:

– Identify side effects in your React apps.

– Understand and use the useEffect() Hook.

– Utilize the different features and concepts related to the useEffect() Hook to avoid bugs and optimize your code.

– Handle side effects related and unrelated to state changes.

Introduction

While all React examples previously covered in this book have been relatively straightforward, and many key React concepts were introduced, it is unlikely that many real apps could be built with those concepts alone.

Most real apps that you will build as a React developer also need to send HTTP requests, access the browser storage and log analytics data, or perform any other kind of similar task. And with components, props, events, and state alone, you'll often encounter problems when trying to add such features to your app. Detailed explanations and examples will be discussed later in this chapter, but the core problem is that tasks like this will often interfere with React's component rendering cycle, leading to unexpected bugs or even breaking the app.

This chapter will take a closer look at those kinds of actions, analyze what they have in common, and most importantly, teach you how to correctly handle such tasks in React apps.

What's the Problem?

Before exploring a solution, it's important to first understand the concrete problem.

Actions that are not directly related to producing a (new) user interface state often clash with React's component rendering cycle. They may introduce bugs or even break the entire web app.

Consider the following example code snippet:

import { useState } from 'react';
import classes from './BlogPosts.module.css';
async function fetchPosts() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  const blogPosts = await response.json();
  return blogPosts;
}
function BlogPosts() {
  const [loadedPosts, setLoadedPosts] = useState([]);
  fetchPosts().then((fetchedPosts) => setLoadedPosts(fetchedPosts));
  return (
    <ul className={classes.posts}>
      {loadedPosts.map((post) =>...

Understanding Side Effects

Side effects are actions or processes that occur in addition to another "main process". At least, this is a concise definition that helps with understanding side effects in the context of a React app.

Note

You can also look up a more scientific definition here: https://en.wikipedia.org/wiki/Side_effect_(computer_science).

In the case of a React component, the main process would be the component render cycle in which the main task of a component is to render the user interface that is defined in the component function (the returned JSX code). The React component should return the final JSX code, which is then translated into DOM-manipulating instructions.

For this, React considers state changes as the trigger for updating the user interface. Registering event handlers such as onClick, adding refs, or rendering child components (possibly by using props) would be other elements that belong to this main process—because all...

Dealing with Side Effects with the useEffect() Hook

In order to deal with side effects such as the HTTP request shown previously in a safe way (that is, without creating an infinite loop), React offers another core Hook: the useEffect() Hook.

The first example can be fixed and rewritten like this:

import { useState, useEffect } from 'react';
import classes from './BlogPosts.module.css';
async function fetchPosts() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  const blogPosts = await response.json();
  return blogPosts;
}
function BlogPosts() {
  const [loadedPosts, setLoadedPosts] = useState([]);
  useEffect(function () {
    fetchPosts().then((fetchedPosts) => setLoadedPosts(fetchedPosts));
  }, []);
  return (
    <ul className={classes.posts}>
      {loadedPosts...

Effects and Their Dependencies

Omitting the second argument to useEffect() causes the effect function (the first argument) to execute after every component function execution. Providing an empty array causes the effect function to run only once (after the first component function invocation). But is that all you can control?

No, it isn't.

The array passed to useEffect() can and should contain all variables, constants, or functions that are used inside the effect function—if those variables, constants, or functions were defined inside the component function (or in some parent component function, passed down via props).

Consider this example:

import { useState, useEffect } from 'react';
import classes from './BlogPosts.module.css';
const DEFAULT_URL = 'https://jsonplaceholder.typicode.com/posts';
async function fetchPosts(url) {
  const response = await fetch(url);
  const blogPosts = await response.json();
...

Summary and Key Takeaways

  • Actions that are not directly related to the main process of a function can be considered side effects.
  • Side effects can be asynchronous tasks (for example, sending an HTTP request), but can also be synchronous (for example, console.log() or accessing browser storage).
  • Side effects are often needed to achieve a certain goal, but it's a good idea to separate them from the main process of a function.
  • Side effects can become problematic if they cause infinite loops (because of the update cycles between effect and state).
  • useEffect() is a React Hook that should be used to wrap side effects and perform them in a safe way.
  • useEffect() takes an effect function and an array of effect dependencies.
  • The effect function is executed directly after the component function was invoked (not simultaneously).
  • Any value, variable, or function used inside of an effect should be added to the dependencies array.
  • Dependency array exceptions...

Apply What You Learned

Now that you know about effects, you can add even more exciting features to your React apps. Fetching data via HTTP upon rendering a component is just as easy as accessing browser storage when some state changes.

In the following section, you'll find an activity that allows you to practice working with effects and useEffect(). As always, you will need to employ some of the concepts covered in earlier chapters (such as working with state).

Activity 8.1: Building a Basic Blog

In this activity, you must add logic to an existing React app to render a list of blog post titles fetched from a backend web API and submit newly added blog posts to that same API. The backend API used is https://jsonplaceholder.typicode.com/, which is a dummy API that doesn't actually store any data you send to it. It will always return the same dummy data, but it's perfect for practicing sending HTTP requests.

As a bonus, you can also add logic to change the text...

lock icon The rest of the chapter is locked
You have been reading a chapter from
React Key Concepts
Published in: Dec 2022 Publisher: Packt ISBN-13: 9781803234502
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.
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}