Search code examples
reactjstypescriptusecallback

Getting a Typescript error with useCallback() in Visual Studio Code


I'm new to React hooks, and have run across this code: const multiply = useCallback((value: number) => value * multiplier, [multiplier]); (from https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d)

This is confusing to me and Visual Studio Code, which reports this error: Cannot find name 'multiplier'. Did you mean 'multiply'?ts(2552)

I feel that I know Typescript reasonably well, but I don't understand [multiplier] or how to resolve this issue. I suppose it's correct Typescript (it does seem to actually compile). Can someone explain to me how this syntax works and how to get Visual Code Studio to accept it? Or if it needs to be fixed?


Solution

  • The full example on that page is this:

    const multiplier = 2;
    // inferred as (value: number) => number
    const multiply = useCallback((value: number) => value * multiplier, [multiplier]);
    

    Which compiles just fine.

    multiplier here is just a variable that is defined somewhere. It could be a constant like the code above or something pulled from component state, or come from an API call. There's nothing special about it, it's just a local variable that needs to be defined before you use it.

    And [multiplier] just means that multiplier is the only value in an array. In this case, the value [2]. It represents the dependencies of the callback. If any dependencies change, the callback will be recreated. So there needs to be a way to pass in multiple dependencies. In this case, there is only one: multiplier. So you pass in an array with a single item as [multiplier].