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