Blog>
Snippets

Optimizing React Components with TanStack Store's useQuery Hook

Illustrate the use of the useQuery hook from TanStack Store to fetch data and render a React component, showcasing the reduction in boilerplate code.
import { useQuery } from '@tanstack/react-query';
import React from 'react';
Import useQuery hook from TanStack React Query and React.
function fetchUserData() {
  return fetch('https://api.example.com/user')
    .then(res => res.json());
}
Define a function to fetch user data from an API.
function UserDataComponent() {
  const { data, error, isLoading } = useQuery(['userData'], fetchUserData);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;

  return (
    <div>
      <h1>User Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
Create a React component that uses the useQuery hook to fetch and display user data.
export default UserDataComponent;
Export the component for use in other parts of the application.