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

Managing Data

In this chapter, we will explore two beneficial tools: the React Context API and React Suspense. The Context API simplifies the process of sharing data across our entire application without the need to pass it down through multiple layers. On the other hand, React Suspense enables specific parts of our app to wait for certain actions before being displayed, resulting in a smoother loading experience.

By utilizing these tools collectively, we can enhance data management and improve the overall performance of our app. Join us on this journey as we delve into the efficient handling of data in React.

We will cover the following topics in this chapter:

  • The React Context API
  • How to consume a context with useContext
  • How to use React Suspense with SWR (Stale-While-Revalidate)
  • How to use Redux Toolkit

Managing Data

In this chapter, we will explore two beneficial tools: the React Context API and React Suspense. The Context API simplifies the process of sharing data across our entire application without the need to pass it down through multiple layers. On the other hand, React Suspense enables specific parts of our app to wait for certain actions before being displayed, resulting in a smoother loading experience.

By utilizing these tools collectively, we can enhance data management and improve the overall performance of our app. Join us on this journey as we delve into the efficient handling of data in React.

We will cover the following topics in this chapter:

  • The React Context API
  • How to consume a context with useContext
  • How to use React Suspense with SWR (Stale-While-Revalidate)
  • How to use Redux Toolkit

Technical requirements

To complete this chapter, you will need the following:

  • Node.js 19+
  • Visual Studio Code

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

Introducing the React Context API

The React Context API has come a long way since it was first introduced as an experimental feature. Since version 16.3.0, it has been officially added to React and has become a game-changer for many developers. In fact, many are now using the new Context API instead of Redux. The Context API allows you to share data between components without having to pass a prop to every child component.

To illustrate how to use the new Context API, let’s revisit the example from Chapter 8, React Hooks, where we fetched GitHub issues using React Hooks, but this time by using the Context API instead.

Creating our first context

The first thing you need to do is to create the issue context. For this, you can create a folder called contexts inside your src folder, where you will add the Issue.tsx file.

Then, you need to import some functions from React and axios:

import { FC, createContext, useState, useEffect, ReactElement, useCallback }...

Consuming context with useContext

If you’ve already placed IssueProvider in App.tsx, now you can consume your context in your Issues component by using the useContext Hook.

Notice here that we are importing the IssueContext context (between { }):

// Dependencies
import { FC, useContext } from 'react'
// Contexts
import { IssueContext, Issue } from '../contexts/Issue'
const Issues: FC = () => {
  // Here you consume your Context, and you can grab the issues value.
  const { issues, url } = useContext(IssueContext)
  return (
    <>
      <h1>ContentPI Issues from Context</h1>
      {issues.map((issue: Issue) => (
        <p key={`issue-${issue.number}`}>
          <strong>#{issue.number}</strong> {' '}
          <a href={`${url}/${issue.number}`}>{issue.title}</a> {' '}
          {issue.state}
        </p>
      ))}
    </>
  )
}
export default Issues

If you...

Introducing React Suspense with SWR

React Suspense was introduced in React 16.6. Suspense lets you suspend component rendering until a condition is met. You can render a loading component or anything you want as a fallback of Suspense.

Right now, there are only two use cases for this:

  • Code splitting: When you split your application and you’re waiting to download a chunk of your app when a user wants to access it.
  • Data fetching: When you’re fetching data.

In both scenarios, you can render a fallback, which can normally be a loading spinner, some loading text, or even better, a placeholder skeleton.

Introducing SWR

Stale-While-Revalidate (SWR) is a React Hook for data fetching; it is an HTTP cache invalidation strategy. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally, return with up-to-date data, and was developed by Vercel, the company that created Next.js.

...

Redux Toolkit: a modern approach to Redux

Redux Toolkit is the official, opinionated, and batteries-included toolset for efficient Redux development. It was created to help developers write better and more efficient Redux code with less boilerplate. In this section, we’ll explore the key features of Redux Toolkit, along with code examples to demonstrate how to use it in your application.

Key features

Redux Toolkit comes with several key features that simplify the Redux development process:

  • configureStore: A function that sets up a Redux store with sensible defaults.
  • createSlice: A function that automatically generates action creators and reducers based on a provided configuration.
  • createAction: A utility function to create action creators with a specific type and payload.
  • createReducer: A utility function that simplifies reducer creation using Immer, enabling direct state manipulation.

Getting started

First, install Redux Toolkit...

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