Is there any point in specifying a second argument to useEffect, such as a function that never changes?
useEffect(
() => {
const dispatch(asyncTestFunction({ data }))
},
[data, dispatch],
);
In this case, why do we put dispatch as the second argument?
The documentation states that it is not necessary to include functions such as useState.
2
Answers
Those
[data, dispatch]
are called dependencies not arguments, which means youruseEffect
is dependent on them changing for it to be triggered.Leave the array
[]
empty, youruseEffect
will be called only when the page loads. In your case you can use only[data]
so that when data changes youruseEffect
is triggered.You don’t need to add functions as dependencies because that may cause the
useEffect
to be called infinitely.Think of it like this "when
data
changes I want todispatch
" but if I say "whendispatch
changes I wannadispatch
again". See how that can cause an infinite loop.Your implementation might be like this ,
Here the linter(eslint) is satisfied as you are adding
dispatch
to deps array.The linter doesn’t know whether the dispatch reference will remain the same or change in subsequent renders, even though it is stable since the store was created.