Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
$9.99 | ALL EBOOKS & VIDEOS
Over 7,000 tech titles at $9.99 each with AI-powered learning assistants on new releases
State Management with React Query
State Management with React Query

State Management with React Query: Improve developer and user experience by mastering server state in React

By Daniel Afonso
$23.99 $9.99
Book May 2023 228 pages 1st Edition
eBook
$23.99 $9.99
Print
$29.99
Subscription
$15.99 Monthly
eBook
$23.99 $9.99
Print
$29.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon AI Assistant (beta) to help accelerate your learning
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : May 12, 2023
Length 228 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781803231341
Vendor :
Facebook
Category :
Table of content icon View table of contents Preview book icon Preview Book

State Management with React Query

What Is State and How Do We Manage It?

State is a mutable data source that can be used to store data in a React application and can change over time and be used to determine how your component renders.

This chapter will refresh your existing knowledge about state in the React ecosystem. We will review what it is and why it is needed, and understand how it helps you build React applications.

We’ll also review how you can manage state natively in React by using the useState hook, the useReducer hook, and React Context.

Finally, we’ll offer brief descriptions of the common state management solutions such as Redux, Zustand, and MobX and understand why they have been created and the main common concept they all share.

By the end of this chapter, you will have either learned or remembered everything about state necessary to proceed in this book. You will also notice a pattern in how state is managed between different state management solutions and meet or get reacquainted with a familiar term. Spoiler alert: it is global state.

In this chapter, we’ll be covering the following topics:

  • What is state in React?
  • Managing state in React
  • What do different state management libraries have in common?

Technical requirements

In this book, you are going to see some code snippets. If you want to try them out, you are going to need the following:

  • An integrated development environment (IDE) such as Visual Studio Code.
  • A web browser (Google Chrome, Firefox, or Edge).
  • Node.js. All the code in this book was written with the current LTS version installed (16.16.0).
  • A package manager (npm, Yarn, or pnpm).
  • A React project. If you don’t have one, you can create one with Create React App by running the following command in your terminal:
    npx create-react-app my-react-app

All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/State-management-with-React-Query/tree/feat/chapter_1.

What is state in React?

State is the heart of your React application.

I challenge you to try to build a React application without any type of state. You’d probably be able to do something, but you would soon conclude that props cannot do everything for you and get stuck.

As mentioned in the introduction, state is a mutable data source used to store your data.

State is mutable, which means that it can be changed over time. When a state variable changes, your React component will re-render to reflect any changes that the state causes to your UI.

Okay, now, you might be wondering, “What will I store in my state?” Well, the rule of thumb that I follow is that if your data fits into any of the following points, then it’s not state:

  • Props
  • Data that will always be the same
  • Data that can be derived from other state variables or props

Anything that doesn’t fit this list can be stored in state. This means things such as data you just fetched through a request, the light or dark mode option of a UI, and a list of errors that you got from filling a form in the UI are all examples of what can be state.

Let’s look at the following example:

const NotState = ({aList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  ]}) => {
  const value = "a constant value";
  const filteredList = aList.filter((item) => item % 2 ===
    0);
  return filteredList.map((item) =>
    <div key={item}>{item}</div>);
};

Here, we have a component called NotState. Let’s look at the values we have in there and use our rule of thumb.

The aList variable is a component prop. Since our component will receive this, it doesn’t need to be state.

Our value variable is assigned a string value. Since this value will always be constant, then it doesn’t need to be state.

Finally, the filteredList variable is something that can be derived from our aList prop; therefore, it doesn’t need to be state.

Now that you are familiar with the concept of state, let’s get our hands dirty and understand how can we manage it in React.

Managing state in React

Before diving into some examples, it is important to mention that in this book, all the examples shown are in a React version after 16.8. This is because React Hooks were introduced in this version. Hooks changed the way we write React code and allowed for the appearance of libraries such as React Query, so it makes sense that any examples shown leverage them.

What is React Query?

React Query is a protocol-agnostic collection of hooks for fetching, caching, and updating server state in React.

In this section, I’ll show you how React allows us to handle state in a component and what we should do if we need to share state between components.

Let’s consider the following scenario.

I want to build an application that allows me to count something. In this application, I want to be able to do the following:

  • See the current counter value
  • Increment my counter
  • Decrement my counter
  • Reset the counter

Let’s imagine that we have a React component called App:

const App = () => {
  ...
  return (
    <div className="App">
      <div>Counter: {count}</div>
      <div>
        <button onClick={increment}>+1</button>
        <button onClick={decrement}>-1</button>
        <button onClick={reset}>Reset</button>
      </div>
    </div>

This app provides the UI needed to handle our counter needs, such as a div that we should use to display our count and three buttons with an onClick event waiting for a callback function to perform each of the following actions needed.

We are just missing the heart of this component, which is the state. Natively, React gives us two ways to hold state in our applications: useState and useReducer.

Let’s start by looking at useState.

Managing state with useState

useState is a React Hook that allows you to hold a stateful value. When calling this hook, it will return the stateful value and a function to update it.

Let’s look at an example of how to leverage useState to build the counter application:

const App = () => {
  const [count, setCount] = useState(0);
  const increment = () => setCount((currentCount) =>
    currentCount + 1);
  const decrement = () => setCount((currentCount) =>
    currentCount - 1);
  const reset = () => setCount(0);
  return (
    <div className="App">
      <div>Counter: {count}</div>
      <div>
        <button onClick={increment}>+1</button>
        <button onClick={decrement}>-1</button>
        <button onClick={reset}>Reset</button>
      </div>
    </div>
  );
};

The preceding snippet leverages the useState hook to hold our counter state. When we first call useState, two things are done:

  • The state value is initiated as 0
  • The count state variable is destructured; then, the same is done to the state updater function, called setCount

After this, we declare functions where we use the state updater function, setCount, to either increment, decrement, or reset our state variable.

Finally, we assign our state variable to the respective UI section and pass the callbacks to our buttons’ onClick events.

With that, we have built a simple counter application. Our application will start rendering our count as 0. Every time we click on the buttons, it will execute the respective state update, re-render our application, and display the new count value.

useState is the answer most of the time when you need any state in your React applications. Just don’t forget to apply the “what will I store in my state?” rule of thumb before!

Now, let’s see an example of how to manage state and build the same counter application by using the useReducer hook.

Managing state with useReducer

useReducer is the preferred option when we have a more complex state. Before using the hook, we need to do some setup so that we have everything we need to send to our useReducer hook:

const initialState = { count: 0 };
const types = {
  INCREMENT: "increment",
  DECREMENT: "decrement",
  RESET: "reset",
};
const reducer = (state, action) => {
  switch (action) {
    case types.INCREMENT:
      return { count: state.count + 1 };
    case types.DECREMENT:
      return { count: state.count - 1 };
    case types.RESET:
      return { count: 0 };
    default:
      throw new Error("This type does not exist");
  }
};

In the preceding snippet, we created three things:

  • An initialState object. This object has a property count with 0 as its value.
  • A types object that describes all the action types we will support.
  • A reducer. This reducer is responsible for receiving our state and action. By matching that action with the expected type, we’ll be able to update the state.

Now that the setup is done, let’s create our counter:

const AppWithReducer = () => {
  const [state, dispatch] = useReducer(reducer,
    initialState);
  const increment = () => dispatch(types.INCREMENT);
  const decrement = () => dispatch(types.DECREMENT);
  const reset = () => dispatch(types.RESET);
  return (
    <div className="App">
      <div>Counter: {state.count}</div>
      <div>
        <button onClick={increment}>+1</button>
        <button onClick={decrement}>-1</button>
        <button onClick={reset}>Reset</button>
      </div>
    </div>
  );
};

The preceding snippet leverages the useReducer hook to hold our counter state. When we first call useReducer, three things are done:

  • We indicate to our hook what reducer should be used
  • We initialize our state with the initialState object
  • We destructure the state object and then the dispatch function, which allows us to dispatch an action from the useReducer hook

After this, we create the functions that will be responsible for calling the dispatch function with the expected action.

Finally, we assign our state variable to the respective UI section and pass the callbacks to our buttons’ onClick events.

With these two hooks under your belt, you now know how to manage state in your components.

Now, let’s picture the following scenario: what if you need your counter state to be accessible in other components?

You could pass them by props. But what if this state needs to be sent to five other components and different levels on the tree? Would you be prop-drilling it and passing it to every component?

To deal with this scenario and improve your code readability, React Context was created.

Sharing state with React Context

Context allows you to natively share values between components without having to prop drill them. Let’s learn how to build a context to handle our counter:

import { useState, createContext } from "react";
export const CountContext = createContext();
export const CountStore = () => {
  const [count, setCount] = useState(0);
  const increment = () => setCount((currentCount) =>
    currentCount + 1);
  const decrement = () => setCount((currentCount) =>
    currentCount - 1);
  const reset = () => setCount(0);
  return {
    count,
    increment,
    decrement,
    reset,
  };
};
const CountProvider = (children) => {
  return <CountContext.Provider value={CountStore()}
    {...children} />;
};
export default CountProvider;

In the preceding snippet, we are doing three things:

  • Using the createContext function to create our context.
  • Creating a store. This store will be responsible for holding our state. Here, you can see we leverage the useState hook. At the end of the store, we return an object that contains the functions to do the state updates and create our state variable.
  • Creating a CountProvider. This provider is responsible for creating a provider that will be used to wrap a component. This will allow every component that is inside of that provider to access our CountStore values.

Once this setup has been done, we need to make sure our components can access our context:

root.render(
  <CountProvider>
    <App />
  </CountProvider>
);

The preceding snippet leverages CountProvider, which we created in the previous snippet, to wrap up our App component. This allows every component inside App to consume our context:

import { CountContext } from "./CountContext/CountContext";
const AppWithContext = () => {
  const { count, increment, decrement, reset } =
    useContext(CountContext);
  return (
    <div className="App">
      <div>Counter: {count}</div>
      <div>
        <button onClick={increment}>+1</button>
        <button onClick={decrement}>-1</button>
        <button onClick={reset}>Reset</button>
      </div>
    </div>
  );
};

Finally, in this snippet, we leverage the useContext hook to consume our CountContext. Since our component is rendered inside our custom provider, we can access the state held inside our context.

Every time the state updates inside of our context, React will make sure that every component that is consuming our context will re-render, as well as receive the state updates. This can often lead to unnecessary re-renders because if you are consuming only a variable from the state and for some reason another variable changes, then the context will force all consumers to re-render.

One of the downsides of context is that often, unrelated logic tends to get grouped. As you can see from the preceding snippets, it comes at the cost of a bit of boilerplate code.

Now, Context is still great, and it’s how React enables you to share state between components. However, it was not always around, so the community had to come up with ideas on how to enable state sharing. To do so, state management libraries were created.

What do different state management libraries have in common?

One of the freedoms React offers you is that it does not impose any standards or practices for your development. While this is great, it also leads to different practices and implementations.

To make this easier and give developers some structure, state management libraries were created:

  • Redux promotes an approach focused on stores, reducers, and selectors. This leads to needing to learn specific concepts and filling your project with a bunch of boilerplate code that might impact the code’s readability and increase code complexity.
  • Zustand promotes a custom hook approach where each hook holds your state. This is by far the simplest solution and currently my favorite one. It synergizes with React and fully embraces hooks.
  • MobX doesn’t impose an architecture but focuses on a functional reactive approach. This leads to more specific concepts, and the diversity of practices can lead the developer to run into the same struggles of code structure that they might already suffer from with React.

One common thing in all these libraries is that all of them are trying to solve the same type of issues that we tried to solve with React Context: a way to manage our shared state.

The state that is accessible to multiple components inside a React tree is often called global state. Now, global state is often misunderstood, which leads to the addition of unnecessary complexity to your code and often needing to resort to the libraries mentioned in this section.

At the end of the day, each developer and team have their preferences and choices. Considering React gives you the freedom to handle your state however you want, you must consider all the advantages and disadvantages of each solution before making your choice. Migrating from one to another can take a lot of time and completely change the paradigm of how state is handled in your application, so choose wisely and take your time.

While global state is not the reason why React Query was built, it has an impact on its creation. The way global state is often composed led to the need to manage a specific part of it that has many challenges. This specific part is called server state and the way it was historically handled paved the way to motivate Tanner Linsley to create React Query.

Summary

In this chapter, we became familiar with the concept of state. By now, you should understand the importance of state as the heart of React applications and know how you can manage it natively with the help of useState and useReducer.

You learned that sometimes, you need to share your state with multiple components and that you can do it with Context or by leveraging a third-party state management library. Each of these solutions has its pros and cons, and at the end of the day, it will be a question of developer preference.

In Chapter 2, Server State versus Client State, you will understand more about global state, and you find out that often, our global state is a combination of both server and client state. You will learn what these terms mean, how to identify these states, and what the common challenges associated with them are.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how state is split into server and client state and the common challenges with each
  • Understand how React Query addresses server state challenges by facilitating data fetching and mutations
  • Apply the knowledge gained to improve developer experience and build applications with improved UX

Description

State management, a crucial aspect of the React ecosystem, has gained significant attention in recent times. While React offers various libraries and tools to handle state, each with different approaches and perspectives, one thing is clear: state management solutions for handling client state are not optimized for dealing with server state. React Query was created to address this issue of managing your server state, and this guide will equip you with the knowledge and skills needed to effectively use React Query for state management. Starting with a brief history of state management in the React ecosystem, you’ll find out what prompted the split from a global state to client and server state and thus understand the need for React Query. As you progress through the chapters, you'll see how React Query enables you to perform server state tasks such as fetching, caching, updating, and synchronizing your data with the server. But that’s not all; once you’ve mastered React Query, you’ll be able to apply this knowledge to handle server state with server-side rendering frameworks as well. You’ll also work with patterns to test your code by leveraging the testing library and Mock Service Worker. By the end of this book, you'll have gained a new perspective of state and be able to leverage React Query to overcome the obstacles associated with server state.

What you will learn

Learn about state and how it s often managed Discover how state splits into server state and Client state Solve common challenges with server state using React Query Install and configure React Query and its Devtools Manage server state data fetching by using the useQuery hook Create, update and delete data by using the useMutation hook Discover the use of React Query with frameworks like Next.js and Remix Explore MSW and the Testing Library to test React Query using hooks

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon AI Assistant (beta) to help accelerate your learning
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : May 12, 2023
Length 228 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781803231341
Vendor :
Facebook
Category :

Table of Contents

14 Chapters
Preface Chevron down icon Chevron up icon
1. Part 1: Understanding State and Getting to Know React Query Chevron down icon Chevron up icon
2. Chapter 1: What Is State and How Do We Manage It? Chevron down icon Chevron up icon
3. Chapter 2: Server State versus Client State Chevron down icon Chevron up icon
4. Chapter 3: React Query – Introducing, Installing, and Configuring It Chevron down icon Chevron up icon
5. Part 2: Managing Server State with React Query Chevron down icon Chevron up icon
6. Chapter 4: Fetching Data with React Query Chevron down icon Chevron up icon
7. Chapter 5: More Data-Fetching Challenges Chevron down icon Chevron up icon
8. Chapter 6: Performing Data Mutations with React Query Chevron down icon Chevron up icon
9. Chapter 7: Server-Side Rendering with Next.js or Remix Chevron down icon Chevron up icon
10. Chapter 8: Testing React Query Hooks and Components Chevron down icon Chevron up icon
11. Chapter 9: What Changes in React Query v5? Chevron down icon Chevron up icon
12. Index Chevron down icon Chevron up icon
13. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.