React applications often need to optimize performance, especially when dealing with expensive computations or repeated API calls. With React 18, a new API called cache was introduced to help improve efficiency by memoizing function results. In this article, weโll explore what cache is, how it works, and when to use it.
๐ What is cache
in React?
The cache
function from React is used to memoize function calls so that repeated executions with the same arguments return the previously computed result. This is particularly useful for expensive operations like fetching data, parsing large datasets, or computing values that don't change frequently.
๐ Benefits of Using cache
- Performance Optimization: Avoids unnecessary recomputations.
- Better User Experience: Faster response times for repeated requests.
- Reduced API Calls: Helps prevent redundant network requests.
๐ ๏ธ How to Use cache
Let's start by importing cache
from React:
import { cache } from "react";
Now, let's use it to memoize an API call function:
const fetchUserData = cache(async (userId: string) => {
const response = await fetch(`https://api.example.com/users/${userId}`);
return response.json();
});
๐ How It Works:
- The first time
fetchUserData("123")
is called, it fetches data from the API. - If
fetchUserData("123")
is called again, it returns the cached result instead of making another network request. - If a new
userId
is passed, a new fetch request is made and cached separately.
๐ฅ Practical Use Cases
1๏ธโฃ Caching Expensive Computations
const heavyComputation = cache((num: number) => {
console.log("Computing...");
return num * num * num; // Simulating an expensive calculation
});
console.log(heavyComputation(5)); // "Computing..." then 125
console.log(heavyComputation(5)); // Instantly returns 125 from cac
2๏ธโฃ Caching API Calls in Server Components
In a React Server Component, we can use cache
to reduce redundant data fetching:
import { cache } from "react";
const getUserData = cache(async (userId: string) => {
const res = await fetch(`https://api.example.com/users/${userId}`);
return res.json();
});
export default async function UserProfile({ userId }: { userId: string }) {
const user = await getUserData(userId);
return <div>{user.name}</div>;
}
3๏ธโฃ Memoizing Expensive Derived State
If a component derives expensive state from props, cache
can help optimize re-renders.
const getFilteredList = cache((items: string[], filter: string) => {
return items.filter(item => item.includes(filter));
});
โ ๏ธ Things to Keep in Mind
- Not for Client Components: Works best in server components or functions executed in server environments.
- Data Freshness: Cached results persist until the component reloads or the function arguments change.
- Use in Controlled Cases: Don't overuse itโsome data should always be refetched when needed.
๐ฏ Conclusion
The cache
API in React is a powerful tool for improving performance by memoizing function results. Whether you're optimizing expensive calculations, reducing API calls, or improving SSR performance, cache
is a handy utility to have in your React toolbox.
๐ Have you used cache in your projects? Share your experiences in the comments! ๐
Top comments (0)