DEV Community

Michael De Abreu
Michael De Abreu

Posted on • Edited 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?

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay