添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

React Query is a powerful library for managing server state in your React applications. It allows you to fetch, cache, and update data easily, without having to deal with the complexities of managing state yourself. In this blog post, we'll walk you through how to get started with React Query and how to use it in your own projects.

Step 1: Install React Query

The first step to using React Query is to install it. You can do this by running the following command in your terminal:

npm install react-query
    Enter fullscreen mode
    Exit fullscreen mode

Step 2: Set up the React Query Provider

The next step is to set up the React Query Provider in your application. This provider will allow you to use React Query throughout your application.

To do this, you need to wrap your application with the QueryClientProvider component. This component takes a QueryClient instance as a prop. The QueryClient is the main object that you'll use to interact with React Query.

Here's an example of how to set up the QueryClientProvider:

import { QueryClient, QueryClientProvider } from 'react-query';
const queryClient = new QueryClient();
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      // Your application code goes here
    </QueryClientProvider>
    Enter fullscreen mode
    Exit fullscreen mode

Step 3: Fetching data with React Query

Now that you've set up the QueryClientProvider, you're ready to start fetching data with React Query. The easiest way to do this is to use the useQuery hook.

The useQuery hook takes two arguments: a unique key for your query and a function that fetches your data. Here's an example:

import { useQuery } from 'react-query';
function App() {
  const { isLoading, error, data } = useQuery('todos', () =>
    fetch('https://jsonplaceholder.typicode.com/todos').then(res =>
      res.json()
  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>An error has occurred: {error.message}</p>;
  return (
      {data.map(todo => (
        <li key={todo.id}>{todo.title}</li>
    Enter fullscreen mode
    Exit fullscreen mode

In this example, we're fetching data from the JSONPlaceholder API and displaying it in a list.

Step 4: Updating data with React Query

React Query also makes it easy to update data in response to user actions. The useMutation hook allows you to define a mutation function that updates your data on the server.

Here's an example of how to use useMutation:

import { useMutation, useQueryClient } from 'react-query';
function AddTodo() {
  const [text, setText] = useState('');
  const queryClient = useQueryClient();
  const addTodoMutation = useMutation(
    text =>
      fetch('https://jsonplaceholder.typicode.com/todos', {
        method: 'POST',
        body: JSON.stringify({
          title: text,
          completed: false,
          userId: 1,
        headers: {
          'Content-type': 'application/json; charset=UTF-8',
      }).then(res => res.json()),
      onSuccess: () => {
        queryClient.invalidateQueries('todos');
  const handleSubmit = event => {
    event.preventDefault();
    addTodoMutation.mutate(text);
    setText('');
  return (
    <form onSubmit={handleSubmit}>
<input
  type="text"
  value={text}
  onChange={event => setText(event.target.value)}
<button disabled={addTodoMutation.isLoading}>Add Todo</button>
  </form>
    Enter fullscreen mode
    Exit fullscreen mode

In this example, we're defining a mutation function that adds a new todo to our API. When the mutation is successful, we invalidate the todos query to refetch the data and update the UI.

Step 5: Caching data with React Query

One of the most powerful features of React Query is its caching system. React Query automatically caches your data and keeps it up to date as you make requests to your API.

Here's an example of how to use caching with React Query:

import { useQuery } from 'react-query';
function App() {
  const { isLoading, error, data } = useQuery('todos', () =>
    fetch('https://jsonplaceholder.typicode.com/todos').then(res =>
      res.json()
  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>An error has occurred: {error.message}</p>;
  return (
      {data.map(todo => (
        <li key={todo.id}>{todo.title}</li>
    Enter fullscreen mode
    Exit fullscreen mode

In this example, we're using the same useQuery hook as before, but now React Query is automatically caching our data. When we make subsequent requests for the todos data, React Query will return the cached data instead of making a new request.

Step 6: Conclusion

That's it! You've now learned how to get started with React Query and how to use it to fetch, update, and cache data in your React applications.

React Query is a powerful tool that can save you a lot of time and effort in managing your application's state. With its easy-to-use API and powerful caching system, it's definitely worth considering for your next project.

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 - 2024.