Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useEffect run conditionally

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());
  }
}, []);
like image 805
Florestan Korp Avatar asked Feb 03 '26 10:02

Florestan Korp


1 Answers

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.
like image 106
Trung Nguyen Avatar answered Feb 06 '26 01:02

Trung Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!