Skip to content
Advertisement

Infinite loop react Js ,use useEffect after i put on parameter with useSelector contains data of array

i wanna ask about my case using useEffect Hook and put on params with useSelector. i really don’t know about this infinite loop after i put on my variables contains useSelector that have bunch of data array from redux. I have intention to put on that variables on parameter useEffect, because i want to directly update data and the data display on the same page.

 // this itemGroup have all of data from getGroup 
 const itemGroup = useSelector(selectGroup);

//this function call get api Data and dispatch to initial state
  const callFunction = () => {
    dispatch(getGroup());
  };
  
  useEffect(() => {
    callFunction();
    // this console.log getting infinite loop after put on itemGroup as parameter useEffect
    console.log()
  }, [itemGroup]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Advertisement

Answer

it is because you pass your store state as a dependency to useEffect. On updating the store state you are dispatching the action named callFunction which might be updating your store state again, which triggers useEffect and useEffect again dispatch callFunction which creates a loop.

just pass empty array to useEffect:

useEffect( () =>{ callFunction() },[])

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement