- create a component cache Context:
const MyComponentCacheContext = React.createContext() ;
2. 设定一个构成部分Cache Provider,并给切一个内值{}(危险目标):
function MyComponentCacheProvider (props){
//we create this in step 3
const [cache,dispatch]= React.useReducer(MyComponentCacheReducer,{})
const value =[cache,dispatch]
return <MyComponentCacheContext value={value} {...props}/>
}
3.we will make the cache look like this => {{index:data},{index:data},...}
so create a component cache Reducer that return the desired shape
:
function MyComponentCacheReducer (state,action) {
switch(action.type){
case ADD-TO-CACHE :
return {...state,[action.index]:action.data}
default :{
throw new Error (`unhandled action type ${action.type}`)
}
}
}
4.let s make all the code above within a custome hook so we can make it reusable:
function useMyComponentCache(){
const MyContext = React.useContext(MyComponentCacheContext)
if(!MyContext){
throw new Error (`useMyComponentCache must be within a MyComponentCacheProvider`)
}
return MyContext
}
5.let s customize your Component function so we can use the code above :
function MyComponent({ index }) {
const [data, setData] = useState( );
const [cache ,dispatch]= useMyComponentCache()
useEffect(() => {
if(cache[index]){
return setData(cache[index])
}else{
//here we fetch data --then--> we store it into the cache immedialty
const dataFetcher=fetchData(index).then(
data =>{
dispatch({type: ADD-TO-CACHE ,index,data})
return data
}
)
// updating state
const PromiseHandler =React.useCallback(
promise=>{
promise.then(
data => {
setData(data)
},
)
}
,[setData])
// Execution-Time
PromiseHandler(dataFetcher)
}
}, [cache,dispatch,index,PromiseHandler,setData]); // i assume that fetchData is
//a stable internal module so i didn t put it to the dependecies list
return <h1>{data}</h1>;
}
6.rendering step :put your component within CacheProvider !!!
function App(){
return ( <MyComponentCacheProvider>
<MyComponent index={0} />
</MyComponentCacheProvider>
)
}