DEV Community šŸ‘©ā€šŸ’»šŸ‘Øā€šŸ’»

DEV Community šŸ‘©ā€šŸ’»šŸ‘Øā€šŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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?

Latest 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 Author

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.

This post blew up on DEV in 2020:

js visualized

šŸš€āš™ļø JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! šŸ„³

Happy coding!