0

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

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
Person
  • 2,190
  • 7
  • 30
  • 58

2 Answers2

1

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

thathat
  • 475
  • 2
  • 6
  • 7
0

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.

ravibagul91
  • 20,072
  • 5
  • 36
  • 59