DEV Community

Cover image for ๐Ÿš€ Optimizing React Performance with cache API
Saiful Islam
Saiful Islam

Posted on

๐Ÿš€ Optimizing React Performance with cache API

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! ๐Ÿš€

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs