DEV Community

Discussion on: Concrete example for React.useImperativeHandle

Collapse
 
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.current.stepUp()
  }, [ref])

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

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

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

codesandbox

Collapse
 
poeticgeek profile image
Yoav Niran

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)