Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 559
Nikita Avatar asked Jul 10 '19 10:07

Nikita


People also ask

What happens if you don't use dependency array in useEffect?

So what happens when the dependency array is empty? It simply means that the hook will only trigger once when the component is first rendered. So for example, for useEffect it means the callback will run once at the beginning of the lifecycle of the component and never again.

Does useEffect work with arrays?

This array will re-run useEffect, if the values inside it changes. This will work perfectly fine when the values passed in the dependency array are of type boolean, string or numbers. But it will have some gotchas when you are dealing with complex values such as objects or arrays.

How do you pass an array in useEffect?

To pass an array to useEffect dependency list in React, we can pass in the array state into the dependencies list. We have the nums array state we created with the useState hook. Then we call useEffect with a callback that logs the current value of nums .

Can useEffect depend on props?

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn't depend on any values from props or state, so it never needs to re-run.


1 Answers

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

like image 199
Fyodor Avatar answered Oct 17 '22 21:10

Fyodor