#Getting started with TanStack in React

7 messages · Page 1 of 1 (latest)

unreal ore
#

Hello, I was recommended to use TanStack as a "data fetching" library to be used in react rather than use the useEffect hook to fetch data from my database.

I have some questions. Why is it recommended to use TanStack to do such thing rather than do everything from scratch? What are the benefits it provides please... would really appreciate if someone can give a contrast between a code not using TanStack vs one using it.

Also, I notice that TanStack has a lot of "things" like router etc, currently I'm using react-router, I was wondering which properties should I use to use TanStack as a "data fetching" library pls.

Finally, would really appreciate if someone can share me any docs related on how to get started with TanStack :c

cloud beacon
#
import { getUserServerFn } from "@/functions/auth";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";

type User = Awaited<ReturnType<typeof getUserServerFn>>["user"];

export const WithoutTanstackQuery = () => {
  const [state, setState] = useState<User>(undefined);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isError, setIsError] = useState<boolean>(false);

  useEffect(() => {
    setIsLoading(true);

    fetch("/api/user")
      .then((response) => response.json() as Promise<User>)
      .then((user) => setState(user))
      .catch(() => setIsError(true))
      .finally(() => setIsLoading(false));
  }, []);
};

export const WithTanstackQuery = () => {
  const {
    data: state,
    isError,
    isLoading,
  } = useQuery({
    queryKey: ["user"],
    queryFn: () =>
      fetch("/api/user").then((response) => response.json() as Promise<User>),
    staleTime: 60 * 1000,
  });
};

export const AnotherComponentWithTanstackQuery = () => {
  // If the data was already fetched in the WithTanstackQuery component,
  // then the data won't be fetched again here,
  // it will use the cached data, unless the data is stale

  const {
    data: state,
    isError,
    isLoading,
  } = useQuery({
    queryKey: ["user"],
    queryFn: () =>
      fetch("/api/user").then((response) => response.json() as Promise<User>),
  });
};

You don't need to handle useEffect, loading state, error state, etc. And the data will be cached, so the data won't re-fetch every time.

unreal ore
cloud beacon
#

In this example, I just showed the useQuery hook, but there are a lot more hooks that are very useful

#

like useSuspenseQuery, useInfiniteQuery, etc.