Home > Blockchain >  Do default parameters need to be in useCallback dependency array?
Do default parameters need to be in useCallback dependency array?

Time:01-16

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]
);

In LISTING 3-3: Defaults can’t refer to things in the function body—default-access-body.js
function example(value = x) {
var x = 42;
console.log(value);
}
example(); // ReferenceError: x is not defined
I’ve used var there because it doesn’t have the Temporal Dead Zone; it’s hoisted to the top of the
scope where it’s declared. But the default value expression still couldn’t use it. The reason is that
defaults are evaluated in their own scope, which exists between the scope containing the function and
the scope inside the function, see Figure 3-1. It’s as though the function were wrapped in another
function that handled doing the defaults.

  • Related