0

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?

Scott Schafer
  • 487
  • 3
  • 14
  • 1
    The error isn't so much a type error, but a case of using a variable that you havn't defined. Do you have an earlier line of code that defines the variable `multiplier`, perhaps with a typo? – Nicholas Tower Aug 03 '20 at 18:46

1 Answers1

1

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].

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Oh wow, was just being braindead here - thanks for that. Still, it looks like what I was trying to do won't work, which was to have a component that rendered a list of items, each with their own onClick handler wrapped in useCallback and containing a unique index (to specify what was clicked on). Am I right to think the usual approach is to put each list entry into its own component and pass the index via props? – Scott Schafer Aug 03 '20 at 22:27
  • It happens to the best of us :) – Alex Wayne Aug 03 '20 at 22:28
  • And the worst too. ;) I updated my question with an additional question. – Scott Schafer Aug 03 '20 at 22:32