Using React Query in a Next.js Project

Marickian
By -
0
Using React Query in a Next.js Project

Using React Query in a Next.js Project

As a big fan of React Query, I find it extremely useful in various projects. Despite its extensive capabilities, React Query's primary attraction for me is its simplicity and efficiency in handling data fetching and caching.

Why Use React Query?

React Query stands out for several reasons:

  • Simple setup process.
  • Cached requests make the application feel fast and responsive.

For those new to React Query, let's cover some general concepts first.

Installation

Start by installing React Query and its DevTools:

npm install react-query react-query/devtools

Setup

In a typical React project, you will need to set up a QueryClient and a QueryClientProvider:

import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60000, // 1 minute
    },
  },
});

function MyApp({ Component, pageProps }) {
  return (
    < QueryClientProvider client={queryClient} >
      < Component {...pageProps} />
      < ReactQueryDevtools initialIsOpen={false} / >
    < /QueryClientProvider >
  );
}

export default MyApp;

Using useQuery

The useQuery hook is used to fetch data. It simplifies data fetching by handling states and caching:

import { useQuery } from 'react-query';
import axios from 'axios';

const fetchTasks = async () => {
  const { data } = await axios.get('/api/tasks');
  return data;
};

function TaskList() {
  const { data, error, isLoading } = useQuery(['tasks'], fetchTasks);

  if (isLoading) return 
Loading...
; if (error) return
Error loading tasks
; return ( < ul > { data.tasks.map(task => ( < li key={task.id}>{task.title}< /li> ))} < /ul > ); }

In this example, useQuery accepts a query key and a query function. The query key is used to cache and track the requests, while the query function returns a promise.

Using useMutation

The useMutation hook is used for creating, updating, or deleting data:

import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';

const addTask = async (newTask) => {
  const { data } = await axios.post('/api/tasks', newTask);
  return data;
};

function AddTaskForm() {
  const queryClient = useQueryClient();
  const mutation = useMutation(addTask, {
    onSuccess: () => {
      queryClient.invalidateQueries('tasks');
    },
  });

  const handleSubmit = async (event) => {
    event.preventDefault();
    const title = event.target.elements.title.value;
    mutation.mutate({ title });
  };

  return (
    < form onSubmit={handleSubmit}>
      < input name="title" placeholder="Task title" />
      < button type="submit">Add Task< /button >
    < /form>
  );
}

In this example, the useMutation hook is used to add a new task. It accepts a mutation function and an onSuccess callback to invalidate the query and refresh the task list.

Conclusion

React Query simplifies data fetching and state management in React applications. With its easy setup and powerful features, it helps create fast and responsive applications.

Post a Comment

0Comments

Post a Comment (0)