🚀 Optimizing React Performance with cache API
Saiful Islam

Saiful Islam @saiful7778

About: I am Saiful Islam, a front-end developer skilled in React.js, TypeScript, JavaScript, and Tailwind CSS. I build user-friendly web apps and have worked on Pocket School Quiz, DTR CLI, and DevMingle.

Location:
Lakshmipur, Bangladesh
Joined:
Mar 8, 2024

🚀 Optimizing React Performance with cache API

Publish Date: Feb 13
0 0

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";
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

🔄 How It Works:

  1. The first time fetchUserData("123") is called, it fetches data from the API.
  2. If fetchUserData("123") is called again, it returns the cached result instead of making another network request.
  3. 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
Enter fullscreen mode Exit fullscreen mode

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>;
}
Enter fullscreen mode Exit fullscreen mode

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));
});
Enter fullscreen mode Exit fullscreen mode

⚠️ 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! 🚀

Comments 0 total

    Add comment