DEV Community

Discussion on: Concrete example for React.useImperativeHandle

kentcdodds profile image
Kent C. Dodds

Hey Yoav! I'm not sure you needed to use useImperativeHandle here. Unless I'm missing something, you could just as easily have referenced the given ref by itself:

const NumberInput = forwardRef((props, ref) => {
  const onUp = useCallback(() => {
  }, [ref])

  const onDown = useCallback(() => {
  }, [ref])

  return (
      <TextInput {...props} type="number" ref={ref} />
        <NumberButton onClick={onUp}>⬆️</NumberButton>
        <NumberButton onClick={onDown}>⬇️</NumberButton>
Enter fullscreen mode Exit fullscreen mode

This seems to work just the same for me. Am I missing something?


poeticgeek profile image
Yoav Niran Author

Hi Kent. Sure, in this simplified and specific example. :)
However, what if for example, ref was a function? Then you'd have to check it and deal with both scenarios.

What if ref wasn't passed at all? It could be that NumberInput is needed as a controlled component. You'd still need the internal ref for the stepUp and stepDown methods.

This way, you separate the usage of external and internal ref, and you make the connection if needed very easily (taking care of both function and object flavors)