The Story of React Query - Sous-titres bilingues

Have you ever thought about why a specific piece of technology gets popular?
Usually there's never a single reason, but I do have a theory that I think is one of the primary drivers.
I call it the 5 o'clock rule.
With the o'clock rule,
the level of abstraction for solving a problem will bubble up until it allows the average developer to stop thinking about the problem,
and therefore go home at 5 o'clock.
This is the story of one such example,
a story of how a single developer in a small town in Utah,
in his spare time, created a library that is used in one out of every six React applications.
For context, that means it gets downloaded 3.3 million times a week, and been downloaded 323 times since you started watching this.
That library is React Query.
And in order to better answer how it allows developers to go home at 5 o'clock,
we need to take a closer look at what problems it helps developers to stop thinking about.
Believe it or not, that problem is React.
And to see why, we need to go back to the basics.
In its most fundamental form, React is a library for building a user in the interfaces.
It's so simple that,
historically, the entire mental model has often been represented as a formula where your view is simply a function of your application state.
All you have to do is worry about how the state in your application changes and React will handle the rest.
The primary mode of encapsulation for this concept is the component, which encapsulates both the visual representation of a particular piece of your application.
UI, as well as the state and logic that goes along with it.
By doing so, the same intuition you about creating and composing together functions can directly apply to creating and composing components.
However, instead of composing functions together to get some value, you can compose components together to get some UI.
In fact,
when you think about composition and react,
odds are you can do in terms of this UI composition since it's what React is so good at.
The problem is in the real world, there's more to building an app than just the UI layer.
It's not uncommon to need to compose and reuse non-visual logic as well.
This the fundamental problem that React Hooks were created to solve.
Just like a component enabled the composition and reusability of UI, Hooks enabled the composition.
and reusability of non-visual logic.
The release of Hooks ushered in a new era of React,
the one that I like to call the how the Fokk do we fetch data era.
What's interesting about all of the built-in hooks that React comes with,
as you've probably experienced first-hand,
is that none of them are dedicated to arguably the most common use case for building a web app, Data Fetching.
The closest we can get out of the box with React is Fetching.
data inside a views effect, and then preserving the response with the use state.
You've undoubtedly seen something like this before.
We're some data from the pokey API and showing it to the view.
Simple.
But unfortunately, this is tutorial code, and you can't write tutorial code at work.
The glaring issue is we're not handling the loading or error states.
This leads our app to commit two of the biggest UX since.
Humulative layout shift and the infinite spinner.
The fix for this is pretty simple.
state.
Cool.
Because we've used U's effect to synchronize our local Pokemon state with the Poke API according to ID,
we've taken what has historically been the most complex part of building a app,
an asynchronous side effect, and made it an implementation detail behind simply updating ID.
Unfortunately, even though this is where everyone usually stops, we're not quite done yet.
In fact, as is, our code contains the worst kind of bug, one that is both inconspicuous and deceptively wasted.
But whenever we call fetch, because it's an asynchronous request, we have no idea how long that specific request will take to resolve.
It's completely possible that,
while we're in the process of waiting for a response,
the user clicks one of our buttons, which causes a re-render, which causes our effect to run again with a different ID.
In this scenario, we now have two requests in flight, and no idea which one will resolve first.
In other words, we have a race condition.
To make it worse, you'll also get a flash of the Pokémon that resolves first before the second one.
Before we get if you're enjoying this video and not feel obligated,
you to give us money,
check QuarryG, it's our brand new, interactive, official REAC query course that we built in close collaboration with the REAC query team.
Okay.
the video.
Really what we want to do is tell React to ignore any responses that come from requests that were made in effects that are no longer relevant.
In order to do that, we need a way to know if an effect is the latest one.
If not, then we should ignore the response and not set Pokemon inside of it.
To do that, we can leverage closures along with use-effects-cleanup function.
Whenever the effect runs, let's make a variable called ignore.
Then, whenever the effects cleanup function runs, which will only happen when another request has been made, we'll set ignore to true.
Now all we have to do before we call set Pokemon or set Air is to check if ignore is true,
if it is, we'll just do nothing.
Now, regardless of how many times ID changes, we'll ignore every response that isn't in the most recent effect.
Confusing?
Yes, welcome to use effect hell.
So at this point, we're finished, right?
Not quite.
If were to make a PR with this code at work,
more than likely someone would ask you to extract all the logic for handling the fetch request into a custom hook.
In doing so, you'd probably end up with something like this.
I still remember how proud I was when I first made this abstraction.
That is, until I started using it.
As is,
this hook doesn't address another fundamental problem of using state and effects By default,
the fetch data is only ever local to the component that fetched it.
That's how React works.
Every component will have its own instance of the state, and component has to show a loading indicator to the user while it gets it.
Even worse, it's possible that while fetching to the same endpoint, one request could fail while the other succeeds.
Or, one fetch could lead to data that is different than the subsequent request.
All the predictability that React offers just went out the window.
Now, if you're an experienced reactive, you might be thinking that if the problem is that we're
fetching the same data multiple times, can't we just move that state up to the nearest parent component and pass it down via props?
Or better, put the fetch data on context so that it's available to any component that needs it?
Sure, and if- If did that, we'd probably end up with something like this.
Well, it works, but this is the exact type of code that future you will hate current you for.
Besides all of the context mess, the biggest change that we've made is to the shape of our state.
Because our state now needs to be able to store the data loading in error states for multiple URLs,
we've had to make it an object where the URL itself is the key.
Now every time we call useQuery with the URL, it'll read from the existing state if it exists or fetch if it doesn't.
With that, we've now just introduced a small in-memory cache and predictability has been restored.
Unfortunately, we've traded our predictability problem for an optimization problem.
As you might know,
REIT context isn't a tool that's particularly good at distributing dynamic data throughout an application,
since it lacks a fundamental trait of state managers, being able to subscribe to pieces of your state.
As is,
any component that calls useQuery will be subscribed to the whole query context,
and therefore will re-render whenever anything changes, even if the change isn't related to the URL it cares about.
Also, if two components call useQuery, at the same time unless we can figure out how to dedupe those requests.
Our app will still make two requests since the use effect is still called once per component.
Oh, and since we've introduced a cache, we also need to introduce a way to invalidate it.
And as you may know, cache invalidation is hard.
What started out as a simple innocent pattern for fetching data in a React application has become complexity,
and unfortunately, there's not just one thing to blame.
At this point, one, two, and three should be obvious, let's dive into number four.
Synchronous state is the state that we're typically used to when working in the browser.
It's our state, which is why it's often called client state.
We can rely on it to be instantly available when we need it,
and no one else can manipulate it, so it's always up to date.
All these traits make client-state easy to work with since it's predictable.
There isn't much that can go wrong if we're the only ones who can update it.
Asynchronous state, on the other hand, is state that is not ours.
We have to get it from somewhere else, usually a server.
which is why it's often called server state.
Server state persists, usually in a database, which means it's not instantly available.
This makes managing it, particularly over time, tricky.
Though it's far too common, it's problematic to treat these two kinds of state as equal.
To manage client state in a React app, we have lots of options.
But what are our options for managing server state in a React app?
Historically, there weren't many.
That is, until React Query came along.
Ironically, you may have heard that ReactQuery is the missing piece for data fetching in React.
That couldn't be further from the truth.
In fact, ReactQuery is not a data fetching library.
And that's a good thing.
Because it should be clear by now that data fetching itself is not the hard part.
It's managing that data over time, that is.
And while ReactQuery works with data fetching, a better way to describe it is as an async state manager.
acutely aware of the needs of server state.
In fact, React Query doesn't even fetch any data for you.
You provided a promise,
and React Query will then take the data that that promise resolves with, and make it available wherever you need it throughout your entire application.
From there, it can handle all of the dirty work that you're either unaware of, or you shouldn't be thinking about in the first place.
And the best part about it,
you can stop trying to figure out how use effect works, which is why it solves the five o'clock rule.
If you enjoyed this video, check out QueryGG.
It's our brand new interactive official React Query course that we built in close collaboration with the React Query team.
Langue de traduction
Sélectionner

Débloquez plus de fonctionnalités

Installez l'extension Trancy pour débloquer plus de fonctionnalités, y compris les sous-titres IA, les définitions de mots IA, l'analyse grammaticale IA, la parole IA, etc.

feature cover

Compatible avec les principales plateformes vidéo

Trancy offre non seulement le support des sous-titres bilingues pour des plateformes telles que YouTube, Netflix, Udemy, Disney+, TED, edX, Kehan, Coursera, mais propose également la traduction de mots/phrases IA, la traduction immersive de texte intégral et d'autres fonctionnalités pour les pages web régulières. C'est un véritable assistant d'apprentissage des langues tout-en-un.

Tous les navigateurs de plateforme

Trancy prend en charge tous les navigateurs de plateforme, y compris l'extension du navigateur Safari iOS.

Modes de visualisation multiples

Prend en charge les modes théâtre, lecture, mixte et autres modes de visualisation pour une expérience bilingue complète.

Modes de pratique multiples

Prend en charge la dictée de phrases, l'évaluation orale, le choix multiple, la dictée et d'autres modes de pratique.

Résumé vidéo IA

Utilisez OpenAI pour résumer les vidéos et saisir rapidement le contenu clé.

Sous-titres IA

Générez des sous-titres IA précis et rapides pour YouTube en seulement 3 à 5 minutes.

Définitions de mots IA

Appuyez sur les mots dans les sous-titres pour rechercher des définitions, avec des définitions alimentées par l'IA.

Analyse grammaticale IA

Analysez la grammaire des phrases pour comprendre rapidement le sens des phrases et maîtriser les points de grammaire difficiles.

Plus de fonctionnalités web

En plus des sous-titres vidéo bilingues, Trancy propose également la traduction de mots et la traduction intégrale de texte pour les pages web.

Prêt à commencer

Essayez Trancy aujourd'hui et découvrez ses fonctionnalités uniques par vous-même