Adding React Query to a Next.js Application

Marickian
By -
0
Adding React Query to a Next.js Application

Adding React Query to a Next.js Application

In this guide, we will integrate React Query into a Next.js application. Before we begin, it's important to note that the setup might seem tedious, but it is essentially a boilerplate setup taken directly from the React Query documentation. You only need to do it once, and you can copy and paste the code where needed.

Setting Up the Query Client

First, we need to provide our query client to each page. While this might seem like a downside, remember that it can be copied and pasted across pages. The setup is a bit more complex than in a traditional React application because we are using server components, but the benefits far outweigh the boilerplate.

One significant benefit is that we can use server actions directly in our React Query code. When setting up the query or mutation function, we can use server actions because they return a promise.

Step-by-Step Setup


// Import required modules
import { useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';

// Initialize Query Client
const [queryClient] = useState(() => new QueryClient({
    defaultOptions: {
        queries: {
            staleTime: 1000 * 60, // 1 minute
        },
    },
}));

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

export default MyApp;
        

Setting Up React Query for Each Page

For each page, we need to import and set up React Query components. Here is the boilerplate code for setting up React Query on a page:


// Import required modules
 
 import { dehydrate, Hydrate, QueryClient } from 'react-query';

// Server-side code to fetch initial data
 
 export async function getServerSideProps() {
    const queryClient = new QueryClient();

    // Prefetch any required data
    await queryClient.prefetchQuery('key', fetchDataFunction);

    return 
    {
       props: 
      	{
             dehydratedState :  dehydrate(queryClient),
        },
    };
}

// Wrap your page component in the Hydrate component
function Page({ dehydratedState }) {
    const queryClient = new QueryClient();

    return (
        < Hydrate state={dehydratedState} >
            < YourComponent / >
        < /Hydrate >
    );
}

export default Page;
        

Creating a Mutation Function

Let's set up a placeholder for our generate chat response function, which we'll eventually use to communicate with OpenAI:


// utils/actions.js
import { useServer } from 'react-query';

export const generateChatResponse = async (chatMessage) => {
    console.log(chatMessage);
    return 'Awesome';
};
        

Now, in your chat component, set up the mutation function:


// Import required modules
import { useMutation } from 'react-query';
import { generateChatResponse } from '../utils/actions';

// Setup mutation in your component
function ChatComponent() {
    const mutation = useMutation(message => generateChatResponse(message));

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

    return (
        < form onSubmit={handleSubmit} >
            < input name="message" / >
            < button type="submit">Send< /button >
        < /form >
    );
}

export default ChatComponent;
        

Conclusion

With the setup complete, you can now use React Query with server actions in your Next.js application. This setup allows you to fetch and mutate data seamlessly while leveraging the power of server-side actions. While it may seem complex initially, the ability to use server actions directly in your client code is incredibly powerful.

Post a Comment

0Comments

Post a Comment (0)