1

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.

4
  • 4
    "I need it to run when array value changes" [props.items] should work if you update the array correctly (i.e. create a new instance when you add,remove or change items). If you are not doing that then you should do it. Commented Nov 19, 2019 at 11:30
  • 1
    You don't need to map inside the dependency array. useEffect(() => { }, [props.items]) should be fine. The props.items don't need to be an array as well. If the reference of props.items changes, the hook will be triggered. Commented Nov 19, 2019 at 11:34
  • Thanks @FelixKling and Vishnu for clarification. It was bugging me for quite some time. Commented Nov 19, 2019 at 11:49
  • Also, with @FelixKling approach, you're preventing a map over the items when it's not necessary. Commented Nov 19, 2019 at 12:51

1 Answer 1

2
// 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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.