Reputation: 105
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)?
Upvotes: 2
Views: 251
Reputation: 1075319
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]
);
In a comment, you've asked:
In your code snippet you reassign the parameter in de body, in my example i do it in the parameters. Doesn't reassigning have different behaviour? Just like how Nullish coalescing (??) for example is different in this case?
No, the above is how default parameter values work. They're evaluated (if needed) during the call to the function, not (for instance) when the function is created. The JavaScript engine inserts code at the very beginning of your function (in a wrapper scope; details) that does the if
and assignment above. (It's very similar to nullish coalescing, but null
doesn't trigger the default, only undefined
does, as in the code above). Here's an example:
function alloc() {
const value = Math.random();
console.log(`alloc called, returning ${value}`);
return value;
}
function example(p = alloc()) {
console.log(`p = ${p}`);
}
console.log("Call with a value other than `undefined` (no call to `alloc`):");
example(42);
console.log();
console.log("Call without a value (calls `alloc`):");
example();
console.log();
console.log("Call with `undefined` (also calls `alloc`):");
example(undefined);
console.log();
console.log("Call with `null` (doesn't call `alloc`):");
example(null);
.as-console-wrapper {
max-height: 100% !important;
}
¹ "effectively" — There are two minor differences:
length
property of your function using default parameter values is 0
, whereas it's 2
in my rewrite.FWIW, here's a small excerpt from the part of my book JavaScript: The New Toys where I explain the parameter scope:
Upvotes: 2