DEV Community

Michael De Abreu
Michael De Abreu

Posted on • Updated on

Why imperative code using refs should be avoided?

Ok. I really thought the title would be self-explanatory, but it seems it isn't. I have a really strong Angular background and to access a child ref inside a component, you can use the ViewChild decorator. Recently I found out about useImperativeHandle. This can be used to create components that can be managed with components refs as you can do with Angular's ViewChild. However, in the docs it says:

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef.

But, why imperative code should be avoided? This can be handy for cases like, a Modal component that can update its own state. Instead of having the parent handling a modal component state, whether is open or closed, the component could do this, and the parent only would have to call methods of the component ref.

I remember reading this like "memory leaks", and the code to be underperformance, but this was back when all React component should use classes. Now that React has first-class support for functional components and has optimizations about when and how a component should be renderer, does this still being a thing?

Top comments (2)

Collapse
 
miccoh1994 profile image
miccoh1994

If you ever found out why I would like to know! useImperativeHandle is a great way for me to seperate, for example, and image drag and drop uploader from the rest of a form twithout having a very messy/verbose form component.

Collapse
 
michaeljota profile image
Michael De Abreu

For what is worth, I've been using that since I post this and I'd noticed no performance issues. It is a small app mostly to show server data, and this is mostly used to control modals.