Please help with a React useEffect infinite loop

I think putting an object in the dependency array causes it to be recreated on every render, so it keeps looping—is that right? Would wrapping it in useMemo fix it?

by 알고리즘고수541

3 answers

Agreed, object dependencies are a new reference on every render, so it's definitely an infinite loop lol

by 초보개발자874 · ▲0

Well, saying useMemo solves everything seems like somewhat dangerous advice. Have you checked the dependency array lint warnings first? And if it's an infinite loop, I think the right order is to log renders to the console and first identify where it's being re-created.

by 디지털노마드851 · ▲0

Wrapping it in useMemo isn't the answer—it's just a temporary fix. The real cause is why that object is being recreated on every render. If the parent is passing an inline object literal, wrapping only the child in useMemo won't help when the parent re-renders. Instead, putting primitive values (like obj.id) in the dependency array rather than the object itself, or lifting the object creation into state/ref, is the fundamental fix. Also, if you're calling setState inside useEffect, that's often the trigger, so I'd need to see the whole code to judge.

by 취준생김씨514 · ▲0