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

3
  • Possible duplicate of react useEffect comparing objects Commented Aug 15, 2019 at 6:29
  • 1
    Can you create a codepen of the issue? Commented Aug 15, 2019 at 7:04
  • @ravibagul91link Comment out useEffect in Child component Commented Aug 15, 2019 at 7:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.