Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
State Management with React Query

You're reading from   State Management with React Query Improve developer and user experience by mastering server state in React

Arrow left icon
Product type Paperback
Published in May 2023
Publisher Packt
ISBN-13 9781803231341
Length 228 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Daniel Afonso Daniel Afonso
Author Profile Icon Daniel Afonso
Daniel Afonso
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

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

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.

You have been reading a chapter from
State Management with React Query
Published in: May 2023
Publisher: Packt
ISBN-13: 9781803231341
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 $19.99/month. Cancel anytime