I want update state only when prop "columns" length changed
useEffect(() => {
if (columns.length !== prevColumns.length) {
// update state
}
}, [columns]);
How can I do it?
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.
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With