The title is explanatory enough, here is an example of such a case:
const handleDateChange = useCallback((startDate = defaultStartDate, endDate = defaultEndDate) => {
// Do something
}, [defaultStartDate, defaultEndDate]);
Do defaultStartDate
and defaultEndDate
need to be included in the dependency array (like in my example)?
CodePudding user response:
Yes, because they're referenced by the function, so the previous version of the function referencing the old values cannot be reused when the values change. It's just like using those variables in the function body.
Your handleDateChange
is effectively¹ the same as this, which makes it more obvious why you need those defaults in the dependency array:
const handleDateChange = useCallback(
(startDate, endDate) => {
if (startDate === undefined) {
startDate = defaultStartDate;
}
if (endDate === undefined) {
endDate = defaultEndDate;
}
// Do something
},
[defaultStartDate, defaultEndDate]
);