0% found this document useful (0 votes)
5 views4 pages

Day15 Comprehension Answers

The document discusses caching in React applications, emphasizing its importance for performance by reducing unnecessary network requests. It covers the integration of TanStack Query, including code snippets for fetching data, the significance of query invalidation after mutations, and the benefits of using DevTools for debugging. Additionally, it highlights the importance of handling loading and error states to enhance user experience.

Uploaded by

y22cs035
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Day15 Comprehension Answers

The document discusses caching in React applications, emphasizing its importance for performance by reducing unnecessary network requests. It covers the integration of TanStack Query, including code snippets for fetching data, the significance of query invalidation after mutations, and the benefits of using DevTools for debugging. Additionally, it highlights the importance of handling loading and error states to enhance user experience.

Uploaded by

y22cs035
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Day-15 Comprehension Questions

1. What is caching in the context of React applications, and why is it


important for performance?

A:
Caching in React (especially with libraries like React Query) refers to storing previously
fetched data so that the app can reuse it without re-fetching from the server. This improves
performance by reducing unnecessary network requests, minimizing latency, and giving the
user faster access to previously viewed or interacted-with data. It also enhances perceived
speed and responsiveness of the app.

2. Write a code snippet using React Query with a type-safe cache key for
fetching product data.

A:

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

interface Product {
id: number;
name: string;
price: number;
}
const PRODUCT_QUERY_KEY = ['products'] as const;

const fetchProducts = async (): Promise<Product[]> => {


const res = await fetch('/api/products');
if (!res.ok) throw new Error('Failed to fetch products');
return res.json();
};

const useProducts = () => {


return useQuery<Product[], Error>({
queryKey: PRODUCT_QUERY_KEY,
queryFn: fetchProducts,
});
};

3. How do caching and memoization together contribute to scalable and


reliable React applications?

A:
Caching prevents unnecessary network requests by storing and reusing server responses,
while memoization prevents unnecessary re-renders and recalculations within the app by
storing the results of expensive computations. Together, they improve both data efficiency
and UI performance, allowing large applications to remain responsive and reliable under
heavy usage.
4. Provide a scenario where memoization could actually hurt performance
instead of helping.

A:
Memoization can hurt performance if applied to fast, cheap computations that don’t justify
the cost of storing and tracking memoized values. For example, memoizing a simple map()
over 5 items adds unnecessary overhead without any real benefit. Overusing useMemo or
useCallback may actually slow down rendering due to extra bookkeeping.

5. What is query invalidation, and why is it important after a mutation?

A:
Query invalidation tells React Query to refetch specific cached data, ensuring the UI reflects
the most recent server state. After a mutation (like adding, updating, or deleting data), the
affected queries must be invalidated so that stale data isn’t shown to users.

6. Summarize the basic workflow for integrating TanStack Query into a new
React project.

A:

1. Install the library: npm install @tanstack/react-query


2. Create a QueryClient and wrap your app with QueryClientProvider
3. Use hooks like useQuery to fetch data and useMutation to post/update
4. Optionally configure staleTime, retry, cache time, and devtools
5. Invalidate queries after mutations to keep data fresh

7. How do you use the useQuery hook to fetch data from an API? Write a
simple code example.

A:

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

const fetchUsers = async () => {


const res = await fetch('/api/users');
if (!res.ok) throw new Error('Failed to fetch users');
return res.json();
};

const Users = () => {


const { data, isLoading, error } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;

return (
<ul>
{data.map((user: any) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};

8. What are the benefits of using TanStack Query DevTools during


development?

A:
TanStack Query DevTools let developers visualize query caches, mutations, background
refetches, stale states, and error handling in real time. It helps in debugging issues, improving
performance tuning, and understanding the data lifecycle without needing console logs.

9. Why is it important to always invalidate relevant queries after a successful


mutation?

A:
Because without invalidation, your app may continue displaying outdated (stale) data.
Invalidating relevant queries forces React Query to fetch the latest data from the server,
ensuring the UI remains accurate and synchronized with backend state.

10. Why is cache invalidation important after a mutation (such as adding or


updating data)?

A:
Cache invalidation prevents stale data from being shown after a mutation. For instance, if you
add a new product, the product list query must be invalidated so the new product appears in
the UI. This maintains consistency between client-side UI and server data.
11. How can you test edge cases like network errors or concurrent updates
when using React Query or SWR?

A:
You can simulate:

 Network failures by disconnecting from the internet or using tools like Chrome
DevTools throttling
 Concurrent updates by triggering multiple mutations or updates from different
tabs/devices
 Use mocking libraries like MSW (Mock Service Worker) to simulate timeouts,
delays, or error codes

React Query also exposes status, error, and isFetching to handle and display such states
during testing.

12. Why is it important to handle loading and error states in your UI?

A:
Handling loading and error states improves user experience and resilience. Without it, users
may see empty screens, stale data, or unexpected behavior. Clear visual feedback builds trust,
helps users understand app state, and allows recovery from failures gracefully.

You might also like