State Management with React Query - Daniel Afonso - E-Book

State Management with React Query E-Book

Daniel Afonso

0,0
21,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 251

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



State Management with React Query

Improve developer and user experience by mastering server state in React

Daniel Afonso

BIRMINGHAM—MUMBAI

State Management with React Query

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Jane D’Souza

Senior Editor: Mark D’Souza

Technical Editor: Simran Udasi

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Sejal Dsilva

Production Designer: Joshua Misquitta

Marketing Coordinators: Namita Velgekar, Nivedita Pandey, and Anamika Singh

First published: May 2023

Production reference: 2250423

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80323-134-1

www.packtpub.com

To my parents, for always supporting me and teaching me not to give up and to work for my dreams. To my brother, you are amazing and have a bright future ahead of you. To my friends, for putting up with me throughout all these years. To my soon-to-be wife, Mariana, for keeping me grounded, for all your love, and, most importantly, for never giving up on me.

– Daniel Afonso

Foreword

I got to know Daniel Afonso when I joined Talkdesk at the end of 2020 as an Agile coach, supporting two teams. I was fortunate enough to work with Daniel, who was then a software developer in one of these teams.

The first thing I noticed about him was his enthusiasm, positive energy, and optimism. You couldn’t help but feel enthusiastic with him around (and the fact that we were all working remotely didn’t change anything)! I’ve worked in IT for 24 years, 16 of those in Agile and Lean – I can tell you that if everyone I’ve met in my professional life had this kind of drive and enthusiasm, I would be out of a job by now.

The second thing that I’ve noticed? Daniel was, is, and (from what I can see) will continue to be a lifelong learner. The so-called “comfort zone” is uncomfortable for him – if he’s not learning/doing something new, he gets bored. I’m like that too. So, despite our age gap (I recall when we were chatting one day and discovered that I am a year younger than Daniel’s mother), we “clicked” very quickly. I don’t have many friends, nor do I use the word “friend” lightly – but I am very grateful to count Daniel as one of my friends.

From then on, Daniel did what the rising stars do. And he’s still rising.

He currently works as a developer advocate, the role he’s always wanted. It takes a very particular mix of skills to be a great developer advocate – you need to be great technically and be an excellent communicator. Not an easy combination to find in the wild, but that’s exactly what Daniel is.

Daniel starts this book by focusing on states and why most apps nowadays are based on states. He proceeds to describe the distinction between client and server states.

After this, he dives into the challenges of changing server states and introduces a new way to deal with them: React Query.

From then, Daniel extensively shows how to use React Query to its full potential, including for data-fetching, mutations, and testing.

Do yourself a favor and enjoy Daniel Afonso’s masterclass – I am sure you will not regret the time invested.

Ricardo Mestre

Director of Agile Operations, Talkdesk

Contributors

About the author

Daniel Afonso is a developer advocate with a full-stack background, having worked with different languages and frameworks on various projects, from IoT to fraud detection. He is passionate about learning and teaching and has spoken at multiple conferences related to React, JavaScript, and testing. In his free time, when he’s not learning new technologies or writing about them, he’s probably reading comics or watching superhero movies and shows.

Thank you to everyone that supported me throughout this journey. Thank you to André Simões and Ricardo Mestre for accepting the invite and joining this adventure with me. Thank you to Mariana for all the understanding and support throughout all the days I had to spend writing.

About the reviewers

André Simões is a passionate frontend engineer who likes to work with cutting-edge technologies and provide smart solutions for challenging problems. He has ~15 years of experience in architecting and developing thoroughly tested web apps and building teams from the ground up. Currently working with React, he has an interest in topics such as state management, micro frontends, and everything that may benefit the end user and/or dev experience.

Paul Blyth is a software engineer with 15 years of professional experience as a core contributor to, and leading teams responsible for, multimillion-dollar web applications for companies such as British Airways, Couchbase, and Spotify. Paul is an advocate for React Query and the huge benefits it brings, having introduced it into large production apps to enrich the UX and streamline code complexity.

Table of Contents

Preface

Part 1: Understanding State and Getting to Know React Query

1

What Is State and How Do We Manage It?

Technical requirements

What is state in React?

Managing state in React

Managing state with useState

Managing state with useReducer

Sharing state with React Context

What do different state management libraries have in common?

Summary

2

Server State versus Client State

Technical requirements

What is global state?

What is client state?

What is server state?

Understanding common challenges with server state

Caching

Optimistic updates

Deduping requests

Performance optimization

Summary

3

React Query – Introducing, Installing, and Configuring It

Technical requirements

What is React Query?

Query

Mutation

How does React Query solve my server state challenges?

Installing React Query

npm

Yarn

pnpm

Script tag

Configuring React Query

QueryClient

QueryClientProvider

Adding React Query Devtools

Floating Mode

Embedded Mode

Enabling Devtools in your production build

Summary

Part 2: Managing Server State with React Query

4

Fetching Data with React Query

Technical requirements

What is useQuery and how does it work?

What is a query key?

What is a query function?

What does useQuery return?

Commonly used options explained

Refetching data with useQuery

Automatic refetching

Manual refetching

Fetching dependent queries with useQuery

Putting it all into practice

Summary

5

More Data-Fetching Challenges

Technical requirements

Building parallel queries

Manual parallel queries

Dynamic parallel queries

Leveraging QueryClient

Query invalidation

Prefetching

Query cancelation

Creating paginated queries

Creating infinite queries

Debugging your queries with Devtools

Summary

6

Performing Data Mutations with React Query

Technical requirements

What is useMutation and how does it work?

What is the mutation function?

What does useMutation return?

Commonly used mutation options explained

Performing side-effect patterns after mutations

How to perform an additional side effect

How to retrigger a query refetch after mutation

How to perform an update to our query data after a mutation

Performing optimistic updates

Summary

7

Server-Side Rendering with Next.js or Remix

Technical requirements

Why should I use React Query with server-side rendering frameworks?

Using the initialData pattern

Applying the initialData pattern in Next.js

Applying the initialData pattern in Remix

Using the hydrate pattern

Applying the hydrate pattern in Next.js

Applying the hydrate pattern in Remix

Summary

8

Testing React Query Hooks and Components

Technical requirements

Configuring Mock Service Worker

Organizing code

Creating an API file

Leveraging query key factories

Creating a hooks folder

Testing components that use React Query

Setting up testing utils

Testing queries

Testing mutations

Testing custom hooks that use React Query

Summary

9

What Changes in React Query v5?

Technical requirements

What are the support changes?

Using only the object format

Removing the logger

Renaming loading to pending

Renaming cacheTime to gcTime

Renaming Hydrate to HydrationBoundary

Next.js hydrate pattern renaming

Remix hydrate pattern changes

Removing keepPreviousData and using placeholderData

Introducing a new way to perform optimistic updates

Introducing maxPages to infinite queries

Summary

Index

Other Books You May Enjoy

Part 1: Understanding State and Getting to Know React Query

State is what makes your applications move. What many of us are not often aware of is that there are different types of state. These different types lead to different challenges when managing the given state. In this part, we will understand more about state and how we manage it. During this process, we will understand that the server and client states have very different challenges that need to be handled separately and with different tools. To deal with server state, we will learn more about the TanStack Query React adapter called React Query and see how to add it to our applications.

This part includes the following chapters:

Chapter 1, What Is State and How Do We Manage It?Chapter 2, Server State versus Client StateChapter 3, React Query – Introducing, Installing, and Configuring It