Person
Person

Reputation: 2259

Infinite loop in useEffect if I pass object as dependency

I have an this piece of code in my React component.

I want to create new object from values of propArray. Like this linter complains that React Hook useEffect has a missing dependency data. But if I supply data to the array of useEffect it causes the infinite loop. I assume it is because I'm updating data object inside useEffect.

What should be done in this case?

const [data, setData] = useState({})
useEffect(() => {
      if (something) {

          const newObj = {
            ...
          }

        setData({data, ...newObj})
      }
}, [something, propArray]);

EDIT

Tried wrapping JSON.stringify(data) and passing it as dependency - works the same.

Also tried useRef

const [data, setData] = useState({})
const latestData = useRef(data)

useEffect(() => {
   if (something) {

      const newObj = {
          ...
      }

      latestData.current = newObj
   }
}, [something, propArray]);

But this way when I'm trying to pass lastestData.current as prop the component it is empty and it is not rerendering

Upvotes: 0

Views: 1634

Answers (2)

ravibagul91
ravibagul91

Reputation: 20755

You can use another version of setNames using previous state, so that we don't need any dependency.

useEffect(() => {
    if (contentLoading) {
      const newNames = { a: "aa" };
      setNames(prevState => ({ ...prevState, ...newNames }));
    }
}, [contentLoading]);

For more on how to use previous state in setState, you can refer this.

Also you can refer When to use functional setState.

Upvotes: 0

thathat
thathat

Reputation: 595

You could write the setData as

    setData(d => ({d, ...newObj}))
    //or maybe you mean
    setData(d => ({...d, ...newObj}))

So it doesn't depend on the current value of data

edit: fixed your sandbox with the above suggestion https://codesandbox.io/s/useeffect-basics-nz0st

Upvotes: 1

Related Questions