Interview Questions

Get ready for your next interview with our comprehensive question library

React Query Interview Questions

Filter by Difficulty

1.

What are the main hooks provided by React Query?

beginner

React Query provides several core hooks:

  • useQuery: For fetching and caching data
  • useMutation: For creating, updating, or deleting data
  • useQueryClient: For accessing the query client instance
  • useInfiniteQuery: For paginated or infinite scrolling data
  • useQueries: For running multiple queries in parallel
  • useIsFetching: For getting the number of currently fetching queries
  • useIsMutating: For getting the number of currently running mutations
    The two most commonly used are useQuery for read operations and useMutation for write operations.
2.

How do you set up React Query in a React application?

beginner

Setting up React Query involves three main steps:

  1. Install the package:
npm install @tanstack/react-query
  1. Create and provide QueryClient:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app components */}
    </QueryClientProvider>
  );
}
  1. Use React Query hooks in components:
import { useQuery } from '@tanstack/react-query';
function Posts() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['posts'],
    queryFn: () => fetch('/api/posts').then(res => res.json())
  });
  if (isLoading) return 'Loading...';
  if (error) return 'Error occurred';
  return <div>{/* Render posts */}</div>;
}
3.

Explain the basic structure of a `useQuery` hook

beginner

The useQuery hook accepts a configuration object with key properties:

const { data, isLoading, error, isError, isSuccess } = useQuery({
  queryKey: ['posts', userId], // Unique identifier for the query
  queryFn: () => fetchPosts(userId), // Function that returns a promise
  enabled: !!userId, // Optional: conditionally enable the query
  staleTime: 5 * 60 * 1000, // Optional: how long data stays fresh
  refetchOnWindowFocus: false // Optional: disable refetch on window focus
});

Key properties:

  • queryKey: Unique identifier used for caching and invalidation
  • queryFn: Async function that fetches the data
  • enabled: Boolean to conditionally run the query
  • staleTime: Time in milliseconds before data is considered stale
    Return values:
  • data: The fetched data
  • isLoading: True during the first fetch
  • error: Error object if the query failed
  • isError/isSuccess: Boolean states for handling different scenarios
4.

What is the difference between `isLoading` and `isFetching` in React Query?

beginner

These two states serve different purposes:
isLoading:

  • True only during the first fetch when there's no cached data
  • False if there's any cached data, even if a background refetch is happening
  • Used to show initial loading states
    isFetching:
  • True whenever any fetch is happening (initial or background)
  • True during background refetches even if cached data exists
  • Used to show loading indicators for any fetching activity
const { data, isLoading, isFetching } = useQuery({
  queryKey: ['posts'],
  queryFn: fetchPosts
});
// First load: isLoading = true, isFetching = true
// Background refetch: isLoading = false, isFetching = true
// With cached data: isLoading = false, isFetching = false

This distinction allows you to show different UI states - a full loading screen for initial loads and a subtle indicator for background updates.

5.

How do query keys work in React Query?

beginner

Query keys are unique identifiers that React Query uses for caching, invalidation, and refetching. They must be arrays and are compared deeply.
Basic structure:

// Simple key
queryKey: ['posts']
// Key with parameters
queryKey: ['posts', userId]
// Key with complex parameters
queryKey: ['posts', { userId, status: 'published' }]

Key principles:

  • Uniqueness: Different keys create separate cache entries
  • Hierarchy: Keys are hierarchical, allowing group operations
  • Deep comparison: React Query compares keys deeply to determine if data should be refetched
    Examples:
// These are different queries with separate cache
queryKey: ['posts'] // All posts
queryKey: ['posts', 1] // Posts for user 1
queryKey: ['posts', 2] // Posts for user 2
// Invalidation example
queryClient.invalidateQueries({ queryKey: ['posts'] }); // Invalidates all post queries
queryClient.invalidateQueries({ queryKey: ['posts', 1] }); // Only user 1's posts

Query keys enable React Query's intelligent caching and make it easy to manage related data.

6.

What is `useMutation` and when would you use it?

beginner

useMutation is used for operations that create, update, or delete data (side effects). Unlike useQuery, mutations don't run automatically and must be triggered manually.
Basic usage:

const mutation = useMutation({
  mutationFn: (newPost) => fetch('/api/posts', {
    method: 'POST',
    body: JSON.stringify(newPost)
  }),
  onSuccess: (data) => {
    // Invalidate and refetch related queries
    queryClient.invalidateQueries({ queryKey: ['posts'] });
  },
  onError: (error) => {
    console.error('Failed to create post:', error);
  }
});
// Trigger the mutation
const handleSubmit = (formData) => {
  mutation.mutate(formData);
};

Key properties:

  • mutationFn: Function that performs the mutation
  • onSuccess: Callback for successful mutations
  • onError: Callback for failed mutations
  • onSettled: Callback that runs regardless of success/failure
    Use cases:
  • Creating new records
  • Updating existing data
  • Deleting records
  • Any operation that modifies server state
7.

How do you handle loading and error states in React Query?

beginner

React Query provides built-in states for handling different scenarios:
Basic approach:

const { data, isLoading, error, isError } = useQuery({
  queryKey: ['posts'],
  queryFn: fetchPosts
});
if (isLoading) return <div>Loading posts...</div>;
if (isError) return <div>Error: {error.message}</div>;
return (
  <div>
    {data.map(post => (
      <div key={post.id}>{post.title}</div>
    ))}
  </div>
);
const { data, isLoading, error, isError } = useQuery({
  queryKey: ['posts'],
  queryFn: fetchPosts,
  retry: 3, // Retry failed requests 3 times
  retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000)
});

// Custom error boundary
if (isError) {
  return (
    <div>
      <h3>Something went wrong</h3>
      <p>{error.message}</p>
      <button onClick={() => refetch()}>Try Again</button>
    </div>
  );
}

For mutations:

const mutation = useMutation({
  mutationFn: createPost,
  onError: (error, variables, context) => {
    // Handle mutation errors
    setErrorMessage(error.message);
  }
});

return (
  <div>
    <button 
      onClick={() => mutation.mutate(postData)}
      disabled={mutation.isPending}
    >
      {mutation.isPending ? 'Creating...' : 'Create Post'}
    </button>
    {mutation.isError && <div>Error: {mutation.error.message}</div>}
  </div>
);
8.

What is the purpose of `staleTime` and `cacheTime` in React Query?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
9.

How do you invalidate queries in React Query?

beginner

Upgrade to Premium to see the answer

Upgrade to Premium
10.

Explain the concept of optimistic updates in React Query

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
11.

How do you implement dependent queries in React Query?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
12.

What are the different ways to update query data in React Query?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
13.

How do you implement infinite queries for pagination?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
14.

What are React Query DevTools and how do you use them?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
15.

How do you handle race conditions in React Query?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
16.

How do you implement background refetching strategies?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
17.

How do you test React Query hooks?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
18.

What are some performance optimization techniques in React Query?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
19.

How do you handle authentication and authorization with React Query?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
20.

What is the `queryOptions` helper and how does it improve TypeScript support?

intermediate

Upgrade to Premium to see the answer

Upgrade to Premium
Showing 1 to 20 of 49 results

Premium Plan

$10.00 /monthly
  • Access all premium content - interview questions, and other learning resources

  • We regularly update our features and content, to ensure you get the most relevant and updated premium content.

  • 1000 monthly credits

  • Cancel anytime