2
Argos
3y

Why useImperativeHandle in React is bad?

I have component A. I have component B which is a child of A.
I have button in component A that should change how component B is displayed.

Usual approach is to set state in A, change it upon click and pass that state as flag via props to B.

But there is another approach via exposing ref to component B using forwardRef() + useImperativeHandle().
And then calling method that belongs to B from A. Like this: bRef.current.changeDisplay()

https://stackoverflow.com/questions...
https://reactjs.org/docs/...
https://github.com/reactjs/...

People on SoF and Docs say that the first way is preferrable. But no one explain why.
Does anyone know why calling child method from parent is considered bad?

Comments
  • 1
    i use the older method but my first instinct was holy shit - more hooks scare me
  • 0
    @Burgundxyz

    Yeah that hook looks ugly, but it is required for functional components to be able to use Ref on them. With class components code looks better.

    This is of course a "+" for the first method

    But my question is more about the idea of calling child method from parent, not the implementation.
  • 1
    I consider any use of ref to be last resort for cases where other solutions do mot work.

    And this useImperitive sounds a bit backwards.

    But I would need to look more into it do give any more relevant opinion.
  • 0
    BC the second might cause a render loop?

    No idea. I'm not UI expert.
Add Comment