logo

AboutWorkCustomer StoriesContactBlogGithub
Using React Query with Next.js App Router
23 Nov 2024

Using React Query with Next.js App Router

ReactWeb Development

Learn how to use TanStack Query with Supabase in Next.js for efficient data fetching, caching, and SSR. Simplify state management, enhance performance, and build robust, scalable web applications.

Next.js has become one of the most popular frameworks for building React applications due to its powerful features like server-side rendering (SSR), static site generation (SSG), and API routes. To handle data fetching efficiently, combining Next.js with libraries like TanStack Query (formerly React Query) and Supabase can significantly enhance your development experience.In this guide, you'll learn how to use TanStack Query with Supabase to fetch and manage data seamlessly in a Next.js application. From setting up your project to handling SSR, we’ve got you covered!

Why Use TanStack Query and Supabase?

TanStack Query simplifies state management for asynchronous data, handling features like caching, background updates, and synchronization with minimal boilerplate. Combined with Supabase, an open-source backend-as-a-service platform, you can achieve efficient and type-safe data fetching with ease.

Key Benefits:

  • Automatic caching and background updates.
  • Out-of-the-box support for SSR and SSG in Next.js.
  • Seamless integration with Supabase’s real-time features.

Prerequisites

This guide assumes you have:

  • Basic knowledge of React and Next.js.
  • A Next.js project set up (version 14.0.3 or later).

Installing Dependencies

To get started, install the required packages:

npm install @supabase/supabase-js @tanstack/react-query @supabase/ssr @supabase-cache-helpers/postgrest-react-query

Setting Up React Query

Create a React Query client and wrap your application with the QueryClientProvider. This ensures the query state is accessible throughout your app.

'use client'

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useState } from 'react';

export const ReactQueryClientProvider = ({ children }) => {
  const [queryClient] = useState(() => new QueryClient({
    defaultOptions: { queries: { staleTime: 60000 } }
  }));
  return {children};
};

Database Setup

Create a countries table in your Supabase database:

create table countries (
  "id" serial primary key,
  "name" text
);

insert into countries (id, name) values 
(1, 'United Kingdom'), 
(2, 'United States'), 
(3, 'Singapore');

Generating TypeScript Types

Use the Supabase CLI to generate TypeScript types:

supabase login
supabase init
supabase link
supabase gen types typescript --linked --schema=public > utils/database.types.ts

Creating Supabase Clients

Set up both client and server Supabase clients to manage data fetching:

// Client Supabase Client
import { createBrowserClient } from '@supabase/ssr';

export default function useSupabaseBrowser() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
  );
}

// Server Supabase Client
import { createServerClient } from '@supabase/ssr';
export default function useSupabaseServer(cookieStore) {
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
    { cookies: cookieStore }
  );
}

Server-Side Data Fetching

To fetch data server-side with React Query, use the prefetchQuery function:

import { dehydrate, QueryClient } from '@tanstack/react-query';

export default async function getServerData(params) {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery('countries', fetchCountries);
  return { props: { dehydratedState: dehydrate(queryClient) } };
}

Client-Side Data Fetching

For client-side fetching, leverage React Query’s useQuery hook:

'use client';

import { useQuery } from '@tanstack/react-query';
import useSupabaseBrowser from './utils/supabase-browser';

export default function Countries() {
  const supabase = useSupabaseBrowser();
  const { data, isLoading } = useQuery('countries', () => supabase.from('countries').select('*'));

  if (isLoading) return 

Loading...;
return

{data.map((country) =>
  • {country.name}
)}; }

Conclusion

Using TanStack Query with Supabase unlocks powerful possibilities for building robust and efficient Next.js applications. From automatic caching to seamless SSR integration, these tools make managing data effortless. Give it a try and watch your productivity soar!

Similar Posts

How to Deploy a Django App to Vercel
DevOpsDjangoWeb Development

How to Deploy a Django App to Vercel

Discover a step-by-step guide to deploying your Django app on Vercel, from setup to configuration, enabling seamless hosting with lightning-fast performance and scalability for modern web applications.

05 Dec 2024

5 min read

Fetching data in React Native
Mobile DevelopmentReactWeb Development

Fetching data in React Native

Learn how to fetch data in React Native using both the native fetch API and the powerful TanStack Query. Explore advanced usage, error handling, caching, and more with code examples for both approaches.

05 Dec 2024

5 min read

Fetching Data in Next.js: A Complete Guide
ReactWeb Development

Fetching Data in Next.js: A Complete Guide

Explore the latest tools, technologies, and trends shaping the world of web development.

23 Nov 2024

5 min read

Stay curious. Stay inspired. Let the stories find you.

Subscribe to get fresh insights, coding tips, and the latest in tech delivered straight to your inbox. Whether you're a beginner or an expert, there's always something new to explore. Be the first to explore stories that inspire, inform, and ignite your imagination