score:7

Accepted answer

TLDR; It's the same and useImperativeHandle just handles all of the ref cases and makes sure the passed value is a ref and not just any value.

Answering your question It handles for you everything that is need when using refs, so it saves some code.


I was looking at the source code of the hooks and looks like under the hood, useImperativeHandle is almost the same as your approach with useEffect.

You can take a look at the hooks and see that they have a HooksDispatcherOnMount, HooksDispatcherOnUpdate and HooksDispatcherOnRerender.

If you look at the functions associated (fooImperativeHandle and fooEffect) you will see that both call the same function (fooEffectImpl).

So apparently, under the hood, it's the same thing, but with when using useImperativeHandle you don't need to handle the part of .current, it already checks for null values, checks if it's a ref and sets in returned value in .current as you can see here.

That is what I got from looking at the source code, but if I'm wrong, please correct me.


Related Query

More Query from same tag