3

How do I prevent my React component from fetching images every time the component is rendered and to fetch them from the store instead? I don't want to get rate limited by doing the API call over and over again, but the problem with useEffect is that it seems to be unaware of the variables being set "outside" of the effect. It seems to completely ignore !images.length and when I log the value for images.length it is always 0 :(

Images.tsx

const dispatch = useDispatch();
const images = useSelector(selectedImages);

useEffect(() => {
  if (!images.length) {
    dispatch(fetchImages());
  }
}, []);
Sarun UK
  • 6,210
  • 7
  • 23
  • 48
Florestan Korp
  • 662
  • 2
  • 12
  • 24

2 Answers2

0

With React hook useMemo you will only call the API whenever you need it

https://www.robinwieruch.de/react-usememo-hook

https://reactjs.org/docs/hooks-reference.html#usememo

0

It is always logging 0 is because you didn't put anything inside dependency array of useEffect so that whenever React re-render your component, it looks inside the useEffect and see nothing inside the dep array, so it just skip running that useEffect.

When you use useEffect, you should declare dependencies in the array of useEffect that are used inside useEffect

const dispatch = useDispatch();
const images = useSelector(selectedImages);

useEffect(() => {
  if (!images.length) {
    dispatch(fetchImages());
  }
}, [images]); // Our deps

So, let's say:

  1. First, by default it will run the useEffect and do all the logics inside that effect. If the images array is empty, calling the API to get images.
  2. Second, images array is not empty anymore, and the 2nd images is different from 1st images array which is empty, so it still run to the useEffect. But it won't fetch images anymore because you have if condition there.
Trung Nguyen
  • 146
  • 2