React use cache is local cache manager to avoid repeat requesting data from server
npm install react-use-cacheReact use cache is an local cache manager to cache response data in memory. It will automatically return previous cached one when requesting the same data from serve to:
- improve performance
- avoid multiple same requests to server to reduce server pressure
Using npm:
``sh`
$ npm install --save react-use-cache
Using yarn:
`sh`
$ yarn add react-use-cache
React hook for cache promises fulfilled value. Use with fetch or axiso together to avoid multiple same request to server. Here is an example to cache blog detail object.
Once a new comment is created, we are able to use updateCache to update the cached object.
Here is the hook interface
`jsx
type DataGenerator
type UseCacheResponse
isFetching: boolean;
data: T | undefined;
updateCache: (nextData: T) => void;
removeCache: () => void;
}
function useCache
`getData
Note: should return a PromiseLike object. It will be invoked only dataKey is changed.
`jsx
// Blog.tsx
import React, { useState } from 'react';
import { useParams } from 'react-router';
import { useCache } from 'react-use-cache';
export default function Blog() {
const { id: blogId } = useParams();
const { isFetching, data: blog, updateCache } = useCache(
() => axios.get(/blog/${blogId}),BLOG_${blogId}
);
const [comment, setComment] = useState
async function addComment() {
const addedComment = await axios.post(/blog/${blogId}/comment, {
comment: comment,
});
const newComments = [...(blog.comments || []), addedComment];
updateCache({
...blog,
comments: newComments,
});
}
return (
not supported now
Please feel free to submit any issues or pull requests.
MIT