Home > other >  useEffect keep rendering workaround
useEffect keep rendering workaround

Time:05-16

I have a small problem. I want to call 4 APIs when the component start rendering so I used use effect for that so I loop my array which has 4 items and at each item I call an API, and each API save the result in selector called filtersCount. The problem is when filtersCount updated the loop start over. How I can prevent this without disabling the eslint ??

const fetchCounts = useCallback(
(item) => {
  if (!filtersCount[item.key]) {
    dispatch(getFilterCount({ filters: item.countFilters, key: item.key }));
  }
},
[dispatch, filtersCount]

);

useEffect(() => {
    exploreItemTypes.map((item) => {
      fetchCounts(item);
    });
  }, [exploreItemTypes, fetchCounts]);

CodePudding user response:

you can use a Ref for this :

const firstRender =useRef(false)
useEffect(() => {
    if(firstRender.current == false){
      exploreItemTypes.map((item) => {
        fetchCounts(item);
       });
      firstRender.current = true 
    }

  }, [exploreItemTypes, fetchCounts]);
  • Related