Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Introducción
¿Ha tenido problemas con la administración del estado del servidor? ¿O se encuentra
escribiendo un código largo y divertido que solo obtiene datos del servidor?
Honestamente, creo que debes mirar react-query si caes en alguna de esta categoría.
React Query is often described as the missing data-fetching library for React, but in
more technical terms, it makes fetching, caching, synchronising and updating server
state in your React applications a breeze.
Prerequisites
You need basic knowledge of the technologies listed below
React
React hooks(elementary)
State Management libraries (elementary)
const globalState = {
user: {},
appSettings: {
appVersion: "",
},
transactions: {
data: [],
transactionLoading: true,
transactionError: null,
};
One question I ask myself before adding a state to a Global state management library is
"Does the app need to know about this data?" and typically, almost all server states don't
pass this test. My app doesn't need to know when the transaction is loading or giving an
error, because this state is most likely used in one component. As these server states
aren't needed globally, the next best decision is to create hooks to help manage basic
server states. Although, this doesn't remove the difficulty in handling multiple server
states like caching, refreshing, retrying, etc. React Query provides a consistent and
straightforward way of managing server state as all of this have been abstracted into the
library.
Installation
npm i react-query
# or
Specimen One
// https://codesandbox.io/s/reverent-sunset-rxwgl?file=/src/App.js
import "./styles.css";
useEffect(() => {
try {
"https://api.github.com/repos/tannerlinsley/react-query"
setData(repoData);
} catch (error) {
setError(error);
} finally {
setLoading(false);
getRepos();
}, []);
return (
<div className="App">
<div>
<h1>{data.name}</h1>
👀
<p>{data.description}</p>
✨
<strong> {data.subscribers_count}</strong>{" "}
🍴
<strong> {data.stargazers_count}</strong>{" "}
<strong> {data.forks_count}</strong>
</div>
</div>
);
return (
<QueryClientProvider client={queryClient}>
<Example />
</QueryClientProvider>
function Example() {
fetch('https://api.github.com/repos/tannerlinsley/react-query').then(res =>
res.json()
return (
<div>
<h1>{data.name}</h1>
👀
<p>{data.description}</p>
✨
<strong> {data.subscribers_count}</strong>{' '}
🍴 {data.forks_count}</strong>
<strong>
</div>
Comparing the functions shows how the useQuery hook eliminates setting three different
state, using a useEffect, catch errors and finally setting loading to false, handling all of
this can be quite cumbersome and the ethos of react-query begins to manifest when
multiple state are managed like an infinite list or paginated server state, refetching the
query.
Specimen Two
Let's take a look at the Rick and Morty example in the docs, as I think this is a more
concise example to highlight how much complexity react-query removes from your
application.
In Examples.js
// https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/
import React from "react";
fetch("https://rickandmortyapi.com/api/episode")
);
return <p>Loading...</p>;
return (
<div>
<Typography variant="h2">Episodes</Typography>
{data.results.map(episode => (
<article key={episode.id}>
<Typography variant="h6">
</Typography>
</Link>
</article>
))}
</div>
);
The episodes data is fetched and rendering is conditionally based on status (the loading
server state, isn't used here as there are some flaws with using loading as a server state,
you can check out Kent Dodds article herehttps://kentcdodds.com/blog/stop-using-
isloading-booleans).
fetch("https://rickandmortyapi.com/api/episode")
);
The "episodes" string is called the Query Keys that helps keep track and manage the
data's cache. The query key should be unique to the query data. If you leave the page then
return, the data will be fetched immediately from the cache (please note that the data
doesn't persist when the application closes) and will be re-fetched in the background,
these are one of the defaults in react-query and is worth taking a look as it might bite you
if as a Beginner.
Most of the other data fetching request in this example will follow this flow, where we try
to fetch data from a server, if it is in the cache we get the data then it fetches the data in
the background if not it fetch the data in the foreground, all of this pristine server state
handling and the methods it exposes are the things that make react-query the right tool to
use for server state.
Summary
So here are reasons you need to use react-query in your React/React Native project are
You don't write long exhaustive code that helps manage server state, react-query
intuitively helps you write cleaner and shorter code as all of that management is
abstracted into react-query.
The application is almost always updated with the most recent server state.
You don't have to deal with useEffects.
Credits
React Query Docs
https://kentcdodds.com/blog/stop-using-isloading-booleans
https://kentcdodds.com/blog/application-state-management-with-react#server-cache-vs-
ui-state
Discussion (1)
Thanks for writing this!
Code of Conduct
•
Report abuse
Benjamín Daniel
LOCALIZACIÓN
tierra
UNIDO
19 de feb. de 2018