Caching API Responses in React
Key Concepts
- Caching
- API Responses
- Cache Policies
- Cache Invalidation
- Local Storage
- Session Storage
- React Query
- Axios Cache Adapter
- Custom Cache Implementation
Caching
Caching is the process of storing data temporarily so that future requests for that data can be served faster. In the context of API responses, caching allows you to store the results of API calls and reuse them without making the same request multiple times.
API Responses
API responses are the data returned from an API call. These responses can be cached to improve performance and reduce the load on the server. Common types of API responses include JSON, XML, and plain text.
Cache Policies
Cache policies define how and when data should be cached. Common cache policies include:
- Time-based: Data is cached for a specific duration (e.g., 5 minutes).
- Usage-based: Data is cached based on how frequently it is accessed.
- Context-based: Data is cached based on the context of the request (e.g., user session).
Cache Invalidation
Cache invalidation is the process of removing or updating cached data when it becomes stale or outdated. This ensures that the application always has the most recent data. Common strategies for cache invalidation include:
- Time-to-live (TTL): Data is automatically invalidated after a set period.
- Event-based: Data is invalidated when a specific event occurs (e.g., data update).
- Manual: Data is manually invalidated by the developer.
Local Storage
Local Storage is a web storage API that allows you to store data on the client side. Data stored in Local Storage persists even after the browser is closed and reopened. This makes it a good option for caching API responses that do not change frequently.
Example:
localStorage.setItem('cachedData', JSON.stringify(data)); const cachedData = JSON.parse(localStorage.getItem('cachedData'));
Session Storage
Session Storage is similar to Local Storage but the data is only available for the duration of the page session. Once the session ends (e.g., the browser is closed), the data is cleared. This is useful for caching data that is only needed for a single session.
Example:
sessionStorage.setItem('cachedData', JSON.stringify(data)); const cachedData = JSON.parse(sessionStorage.getItem('cachedData'));
React Query
React Query is a library that simplifies data fetching and caching in React applications. It provides built-in support for caching API responses, automatic cache invalidation, and background data fetching.
Example:
import { useQuery } from 'react-query'; function fetchData() { return fetch('https://api.example.com/data').then(res => res.json()); } function MyComponent() { const { data, error, isLoading } = useQuery('myData', fetchData); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return <div>{JSON.stringify(data)}</div>; }
Axios Cache Adapter
Axios Cache Adapter is a plugin for Axios that adds caching capabilities to HTTP requests. It allows you to cache responses from API calls and reuse them for subsequent requests.
Example:
import axios from 'axios'; import adapter from 'axios-cache-adapter'; const api = axios.create({ adapter: adapter.setup({ maxAge: 15 * 60 * 1000 // Cache for 15 minutes }) }); api.get('https://api.example.com/data') .then(response => console.log(response.data));
Custom Cache Implementation
Custom cache implementation involves creating your own caching mechanism. This allows you to tailor the caching strategy to your specific needs. Common approaches include using a Map or a custom object to store cached data.
Example:
const cache = new Map(); function fetchData(url) { if (cache.has(url)) { return Promise.resolve(cache.get(url)); } return fetch(url) .then(response => response.json()) .then(data => { cache.set(url, data); return data; }); } fetchData('https://api.example.com/data') .then(data => console.log(data));
Analogies
Think of caching API responses as a library where you store books (API responses) for quick access. When you need a book, you first check the library (cache) before going to the bookstore (server). If the book is in the library and not outdated, you save time by not going to the bookstore.
Another analogy is a restaurant kitchen. The chef (application) checks the pantry (cache) for ingredients (API responses) before sending a waiter (request) to the market (server). If the ingredients are fresh and available, the chef can prepare the dish quickly without waiting for the waiter to return.