Reputation: 147
I am building a small online shopping web app and I have about 10 categories of products e.g. Mens, Womens, Kids etc. I want to memoize the requests. My question is how do I do it? I read about useCallback
hook and I believe that I should use it here, but at the same time since there are like 10 categories how do I keep track for which category should I get from the cache and for which should I make the request? I have just considering declaring useState
hooks for each category and change state for each depending on selected category.
const [productsMensCategory, setProductsMensCategory] = useState([]);
const [productsWomensCategory, setProductsWomensCategory] = useState([]);
const [productsKidsCategory, setProductsKidsCategory] = useState([]);
I have also been thinking that Redux might be useful here.
Could anyone please guide me a bit here, I would like to know how to approach this.
This is how I make a request.
const [products, setProducts] = useState([]);
useEffect(() => {
const getProducts = async (category: string) => {
try {
const response = await getCategoryProducts(category);
console.log(response);
if (response.status === 200) {
setProducts(response.data);
}
} catch (e) {
console.log(e);
}
};
getProducts(handleChangeCategory(section));
}, [section, setProducts]);
Upvotes: 0
Views: 598
Reputation: 502
Good idea to have the data memoized. In my opinion, if at all you can get the data with flags based on date_modified for each category (as server response) you can then set or not set component state.
Something like below
if (response.status === 200 && category_flag_from_server !== current_category_flag_from_state) {
setProducts(response.data);
}
Upvotes: 1
Reputation: 170
If you want these to stay saved even if you reload page you could use localStorage
to make it easy. Redux would be a nice approach to not make another request, but as far as you reload it won't save state.
UseCallback
only memorizes a callback, so if re-render happens this callback remains the same, it only changes if a dependency from its dependencies array changes
Upvotes: 1