Home > OS >  Can't stop an infinite loop at nested component at useEffect hook
Can't stop an infinite loop at nested component at useEffect hook

Time:11-14

I am trying to curb useEffect related to nested components. Here are the components:
Parent (it receives data from API):

const ListOfLots = (props) => {
  const initial = {listLots: props.lots, form: props.form}
  const [lots, setLots] = useState(initial);

  useEffect(() => {
    setLots({
      listLots: props.lots,
      form: props.form
    });
  });

  return (
    <div>
      {
        lots.listLots.map(function(lot) {
          return <Lot key={lot.uuid} lot={lot} procForm={lots.form}/>
        })
      }
    </div>
  )
}

Nested:

const Lot = (props) => {
  const initial = {currLot: props.lot, form: props.form};
  const [lot, setLot] = useState(initial);
  let getWinningBid = (offers) => {
    for (let i = 0; i < offers.length; i  ) {
      console.log("BOOM!!!");
      if (offers[i].isTrue === true) {
        return offers[i].pip;
      }
    }
  }

  return (
    ...
  )
}

While I am using no dependencies at parent's useEffect, I have got an infinite invoking of console.log("BOOM!!!"), that is, of course, unacceptable, but my Nested component rerendered. When I try to use the following type of dependencies at useEffect: [], [lots.form], [lots.listLots] or [lots.listLots.length] my Nested component is not rerendered: it stays blank. So the result is the following: I have an infinite useEffect loop or not-working(?) useEffect.
Is there any way in this case to handle the useEffect?

CodePudding user response:

Use

useEffect(() => {
    setLots({
      listLots: props.lots,
      form: props.form
    });
  }, [props.lots, props.form]);

This triggers the callback only if the value of props.lots, props.form is changed else it won't be triggered on every rerender as in case of no second argument.

A similar question here might help you find better explanations.

  • Related