Keep Two Refs in Sync Using a Custom React Hook

Asís García
Trabe
Published in
2 min readDec 2, 2019
White arrow painted on a blue wall
Photo by Nick Fewings on Unsplash

When you need to get a reference to some component in a React application, you can use a ref.

Whether you use a callback or a ref object (created with either createRef or the useRef Hook), you just need to attach the ref to a component’s ref prop and you are done:

Now, suppose that the users of the Button component above want to get a ref to the DOM element.

You can use forwardRef to get the ref provided by the users:

But now you have a problem. What do you do with that ref? If you assign it to the button, you’ll break the auto-focus functionality. But if you don’t, your users will not get the ref they need.

Luckily, you can update the user provided ref once you own ref is updated:

The implementation above is pretty naive, as it will not work if the user provides a callback ref.

Enter the useSyncedRef Hook

We’ll define a custom Hook that will keep two refs in sync, like we did in the previous snippet, but taking into account the different types of refs:

The custom Hook useSyncedRef takes a ref as a parameter and returns a new one. You can then use the returned ref, and the Hook will take care of keeping the original one in sync 🙂.

This story illustrates why I think Hooks are such an amazing addition to React: the way they compose, with so little friction, yet with so much power… custom Hooks are almost like a React-specific-DSL, and they make building React apps even more delightful than it already was 😄.

--

--