How to build an amazing Tan Stack query web application using tailwind and next js?

ultroneoustech

ultroNeous Technologies

Posted on July 17, 2023

How to build an amazing Tan Stack query web application using tailwind and next js?

What is a TanStack query?

TanStack query is a library for managing and caching asynchronous data in Reactjs developments Service. It provides a declarative API for fetching and caching data that minimizes boilerplate and makes it easy to compose queries. With TanStack query, you can easily handle complex data requirements such as pagination, caching, optimistic updates, and more.

Why should we use TanStack query?

There are several benefits to using TanStack query in your application. Firstly, it simplifies the process of fetching and caching data, reducing the amount of boilerplate code you need to write. Secondly, it improves the performance of your application by using smart caching strategies that reduce the number of network requests. Finally, it allows you to easily handle complex data requirements such as pagination, optimistic updates, and more.

What is the best way to implement the TanStack query?

Actually there’s no best way but there is always a better way to implement the TanStack query and it depends on your specific application requirements.

However, some general best practices include:

  • Use the useEffect() hook to fetch data when the component mounts, and then use TanStack query's useQuery() hook to manage the data.
  • Use TanStack query's caching functionality to reduce the number of network requests.
  • Use TanStack query's built-in loading and error states to provide a great user experience.
  • Consider using TanStack query's pagination and infinite scrolling functionality to handle large datasets efficiently.

Make use of TanStack query's mutations API for managing data updates in your application, which technology supports making applications better using tanstack query.

Here is tech stack for build better Web applications

  1. TanStack query
  2. Prisma ORM
  3. Axios
  4. Next.js Developers
  5. ZOD
  6. MUI
  7. PostgreSQL

Here are some amazing features of tanstack query

  • Protocol/backend agnostic data fetching (REST , GraphQL, promises, etc.)
  • Auto Caching + Refetching (stale-while-revalidate , Window Refocus, Polling/Realtime)
  • Parallel + Dependent Queries
  • Mutations + Reactive Query Refetching
  • Multi-layer Cache + Automatic Garbage Collection
  • Paginated + Cursor-based Queries
  • Load-More + Infinite Scroll Queries w/ Scroll Recovery
  • Request cancellation
  • React Suspense + Fetch-As-You-Render Query Prefetching

Here some notes it’s help you to handle operations

1. Importing and basic usage:

import { useQuery } from '@tanstack/react-query';

const { isLoading, data, error } = useQuery('query_key', async () => {
  const response = await fetch('api_url');
  return response.json();
});
Enter fullscreen mode Exit fullscreen mode

2. Manual Query Refetching:

const { isLoading, data, error, refetch } = useQuery('query_key', async () => {
  const response = await fetch('api_url');
  return response.json();
});

<button onClick={() => refetch()}>Refetch data</button>

// Dependent Queries:
const { isLoading, data, error } = useQuery('query_key_1', async () => {
  const response = await fetch('api_url_1');
  return response.json();
});

const { isLoading: isLoading2, data: data2, error: error2 } = useQuery('query_key_2', async () => {
  const response = await fetch(`api_url_2/${data.id}`);
  return response.json();
}, {
  enabled: !!data,
});

Enter fullscreen mode Exit fullscreen mode

3. Caching:

const { isLoading, data, error } = useQuery('query_key', async () => {
  const response = await fetch('api_url');
  return response.json();
}, {
  cacheTime: 3000, // Cache time in milliseconds
});

Enter fullscreen mode Exit fullscreen mode

4. Polling:

const { isLoading, data, error } = useQuery('query_key', async () => {
  const response = await fetch('api_url');
  return response.json();
}, {
  refetchInterval: 5000, // Refetch interval in milliseconds
  refetchIntervalInBackground: true, // Refetch in background even if tab is inactive
});

Enter fullscreen mode Exit fullscreen mode

5.Query Pagination:

const { isLoading, data: pageData, error, isFetching, fetchNextPage } = useInfiniteQuery('query_key', async ({ pageParam = 0 }) => {
  const response = await fetch(`api_url?page=${pageParam}`);
  return response.json();
}, {
  getNextPageParam: (lastPage, allPages) => lastPage.nextCursor, // Optional for cursor-based pagination
});

<button onClick={() => fetchNextPage()}>Load more</button>
Enter fullscreen mode Exit fullscreen mode

How to integrate react tanstack query using next js ?

Step 1: Install Dependencies

Make sure you have the required dependencies installed. You'll need react, react-dom, next, and @tanstack/react-query packages. You can install them using npm or yarn:
npm install react react-dom next @tanstack/react-query

Step 2: Set up a Next.js Project

Create a new Next.js project if you haven't already:

npx create-next-app my-app
cd my-app
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Custom App Component

Inside the pages directory, create a new file called _app.js (or _app.tsx if using TypeScript). This file will serve as the custom Next.js App component. Import the required dependencies and wrap your application with the QueryClientProvider:

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

const queryClient = new QueryClient();

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

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Step 4: Use useQuery Hook

In your actual page component, import the useQuery hook from @tanstack/react-query. This hook allows you to fetch and manage data using the tanstack query library. Here's an example of how to use it:

import { useQuery } from '@tanstack/react-query';

function MyPage() {
  const { isLoading, isError, data, error } = useQuery('myData', async () => {
    // Fetch data from an API endpoint
    const response = await fetch('/api/data');
    if (!response.ok) {
    throw new Error('An error occurred while fetching the data');
    }
    return response.json();
  });

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (isError) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default MyPage;
Enter fullscreen mode Exit fullscreen mode

In the example above, the useQuery hook is used to fetch data from an API endpoint (/api/data). While the query is in progress, the isLoading flag will be true. If an error occurs during the fetch, the isError flag will be true and the error message will be available in the error object. Once the data is successfully fetched, it will be available in the data object.

Step 5: Start the Next.js Development Server

You can now start the Next.js development server and visit your page:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:3000 to see your page in action. The useQuery hook will automatically manage the fetching and caching of your data.

Remember to adjust the API endpoint and data handling in the useQuery example according to your specific needs.

How to use tanstack query with server side rendering in next js ?

To use tanstack query with server-side rendering (SSR) in Next.js, you can leverage Next.js's getServerSideProps function along with the QueryClient and Hydrate components from @tanstack/react-query.

Here's an example of how you can implement server-side rendering with tanstack query in Next.js:

Step 1: Install Dependencies

Make sure you have the required dependencies installed. You'll need react, react-dom, next, and @tanstack/react-query packages. You can install them using npm or yarn:

npm install react react-dom next @tanstack/react-query
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Custom App Component

Inside the pages directory, create a new file called _app.js (or _app.tsx if using TypeScript). This file will serve as the custom Next.js App component. Import the required dependencies and wrap your application with the QueryClientProvider:

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

const queryClient = new QueryClient();

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

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Page Component

Create a new page component where you want to implement server-side rendering. For example, create a file called index.js (or index.tsx if using TypeScript) inside the pages directory. Import the necessary dependencies and use the getServerSideProps function to fetch the initial data on the server:

import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Hydrate } from 'react-query/hydration'; // Import the Hydrate component

const queryClient = new QueryClient();

function MyPage() {
  const { isLoading, isError, data, error } = useQuery('myData', async () => {
    // Fetch data from an API endpoint
    const response = await fetch('/api/data');
    if (!response.ok) {
      throw new Error('An error occurred while fetching the data');
    }
    return response.json();
  });

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (isError) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export async function getServerSideProps() {
  // Instantiate a new query client
  const ssrQueryClient = new QueryClient();

  // Pre-fetch the initial data and cache it using the query client
  await ssrQueryClient.prefetchQuery('myData', async () => {
    const response = await fetch('/api/data');
    if (!response.ok) {
      throw new Error('An error occurred while fetching the data');
    }
    return response.json();
  });

  // Serialize the query client's state to pass it to the client-side
  const dehydratedState = ssrQueryClient.dehydrate();

  return {
    props: {
      dehydratedState,
    },
  };
}

function IndexPage({ dehydratedState }) {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Hydrate the query client with the serialized state */}
      <Hydrate state={dehydratedState}>
        <MyPage />
      </Hydrate>
    </QueryClientProvider>
  );
}

export default IndexPage;
Enter fullscreen mode Exit fullscreen mode

In the example above, the getServerSideProps function is used to fetch the initial data on the server. The ssrQueryClient.prefetchQuery method is used to fetch the data and cache it using the query client.

On the client-side, the Hydrate component is used to hydrate the query client with the serialized state received from the server. This ensures that the client-side query client has the pre-fetched data available, allowing for a smooth transition between server-side rendering and client-side rendering.

Step 4: Start the Next.js Development Server

You can now start the Next.js development server and visit your page

npm run dev
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:3000 to see your page in action. The useQuery hook will automatically manage the fetching and caching of your data on both the server and the client.

Remember to adjust the API endpoint and data handling in the useQuery and getServerSideProps examples according to your specific needs.

Here is example of tanstack query with Next js and tailwind css
GitHub Link

💖 💪 🙅 🚩
ultroneoustech
ultroNeous Technologies

Posted on July 17, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related