Ivan Cherviakov
Ivan Cherviakov

Reputation: 538

useEffect hook depend on object/array

useEffect working pretty well with primitives, but then I need it to run when array value changes, e.g. I have props.items, then I load items but some ids are different. I tried to use it like this:

useEffect(() => {
}, [...props.items.map((i) => i.id)])

but this solution throws error from react, saying dependency array must not change between calls. Anyone managed to find solid workaround for this situation? Thanks in advance.

Upvotes: 1

Views: 783

Answers (1)

JozeV
JozeV

Reputation: 696

// don't
useEffect(() => {
}, [...props.items.map((i) => i.id)]) // this makes new array with spread operator (...), and then returns another one with .map method

// do
useEffect(() => {
}, [props.items]) // this just points to an existing array we want to watch for changes

Upvotes: 2

Related Questions