当前位置:网站首页>Use cache to reduce network requests
Use cache to reduce network requests
2022-06-11 11:48:00 【Bolodin's Pineapple】
Let's talk about the background first , In a dynamic form , The customer tag data comes from the server , Each time you add an item , The client tag component will request the server to obtain the list of tags to be , When you add items frequently, you will send network requests frequently
How to reduce network requests ? The general idea is to cache the acquired data locally , To be used later , To keep the data fresh , You can set a reasonable “ Shelf life ”, When the cache expires, re request the latest data . Here's the picture
Let's write a pseudocode
function A (){
// ....
// ....
function getData(){
// get data , And set the cache
}
useEffect(()=>{
// If you have a cache
if(xx){
// Judge whether it is overdue
// If expired, request
getData();
}else{
// If there is no cache, request
getData();
}
},[]);
}
Copy code It feels good to see it like this , We have basically realized the functions we want , But there's a problem , In each component, you need to write a piece of code to update the cache , We also need to extract the logic for updating the cache , First, design the scheme , We need three basic elements :
- Request function
- Cache the corresponding key, For read and write caching
- Cache lifetime
According to the above ideas and the three elements , I wrote a version React Cache Hook
// When the same data is used in multiple places , Get data from the server for the first time , Then from SessionStorage Get data in
import { useEffect } from "react";
import { useSessionStorageState, useRequest } from "ahooks";
const useCache = <T>(api: () => void, key: string, expires = 10000) => {
const [cache, setCache] = useSessionStorageState<{
createTime: string,
data: T
}>(key);
const { run, data } = useRequest(api, { manual: true });
useEffect(() => {
if (data) {
setCache({ createTime: new Date().toString(), data: data.data });
}
}, [data]);
useEffect(() => {
if (cache) {
const createTime = new Date(cache.createTime || "");
const time = new Date().getTime() - createTime.getTime();
if (time > expires) {
run();
}
} else {
run();
}
}, []);
return [cache?.data];
};
export default useCache;
Copy code The call is simple
import useCache from "@/hooks/useCache";
//...
const index = (props: Props) => {
const [list] = useCache<Array<Tag>>(getTagList, "customerTags");
}
//...
export default index;
Copy code 边栏推荐
- Elk - x-pack set user password
- 2019年书单
- Lifeifei: I am more like a scientist in physics than an engineer
- [issue 30] shopee golang development experience
- Zhejiang University and Microsoft Asia Research Institute released a new method of video recognition, which can recognize video frame by frame without data marking, or can be used for sign language tr
- Use compiler option '--downleveliteration' to allow iteration of iterations
- JS interview questions - arrow function, find and filter some and every
- The no category parents plug-in helps you remove the category prefix from the category link
- mongoDB 使用
- Display of receiving address list 【 project mall 】
猜你喜欢

Adapter mode -- can you talk well?

JS interview questions - arrow function, find and filter some and every

Node连接MySql数据库写模糊查询接口

msf cs openssl流量加密

Jest unit test description config json
![Set the default receiving address [project mall]](/img/eb/2864b124b66d01849315a367948ed4.png)
Set the default receiving address [project mall]

How to solve the problem that high-precision positioning technologies such as ultra wideband UWB, Bluetooth AOA and RTK cannot be widely used due to their high cost? Adopt the idea of integrated deplo

Cap theory sounds very big, but it's actually very simple

木瓜移动CFO刘凡 释放数字时代女性创新力量

01_ Description object_ Class diagram
随机推荐
Guangdong municipal safety construction data management software 2022 new forms are coming
Hamiltonian graph
Apple mobileone: the mobile terminal only needs 1ms of high-performance backbone
Bark – 自己给自己的 iPhone 发推送提醒 – 最简单的推送提醒服务,开源免费
读取geo表达矩阵
[file upload vulnerability 05] server suffix detection and bypass experiment (based on upload-labs-3 shooting range)
AGCO AI frontier promotion (6.11)
ELK - Hearthbeat实现服务监控
It will be too late if you don't brush the questions. The most complete bat interview questions
Smart sidebar plug-in: Mo widgets
Add auto thumbnail function for WordPress related log plug-ins
木瓜移动CFO刘凡 释放数字时代女性创新力量
JVM class loading process
WordPress重新生成特色图像插件:Regenerate Thumbnails
Centos7.x下安装mysql8遇到的问题Couldn‘t open file /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql-2022
[C language] anonymous/unnamed struct & Union
实用WordPress插件收集(更新中)
No category parents插件帮你去掉分类链接中的category前缀
Use compiler option '--downleveliteration' to allow iteration of iterations
测试cos-html-cache静态缓存插件