Nikita
Nikita

Reputation: 153

How to useEffect only if array length changed?

I want update state only when prop "columns" length changed

  useEffect(() => {
    if (columns.length !== prevColumns.length) {
      // update state
    }
  }, [columns]);

How can I do it?

Upvotes: 15

Views: 16524

Answers (1)

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

You can add the length property to the dependencies of useEffect hook instead of the array itself

useEffect(() => {
      // This code only fires on length change
}, [columns.length]);

And sample

Upvotes: 28

Related Questions