How to share Ref using custom hooks?

Viewed 822

I am trying to keep a global reference on my custom component and use it other places but somehow my hook useHookWithRefValue doesn't return me update ref value, though I have found the workaround with useHookWithRef but I am trying to avoid ref.current every time. What could be reason behind this behaviour?

What is the explanation behind this?

import React from "react";

export const textFieldRef = React.createRef(null);

export function useHookWithRef() {
  return textFieldRef; // Works!!
}

export function useHookWithRefValue() {
  return textFieldRef.current; // Always returns null
}
1 Answers

The reason the second hook always returns null is that it basically returns the value of the textFieldRef.current at the time of its creation, which is null. When the text-field element renders, React tells the ref.current to point to the input element, but this doesn't trigger a re-render and will not make your hook output an updated value.

The first hook on the other hand, returns a reference to the ref object, so if you check the current after React set the ref's current to point to the text-field element, you will get the actual element.

One thing you can do is use a callback ref in order to set your text-field-element on some global state as soon as it renders:

<input ref={inputElement => setTextFieldElement(inputElement)} />

Then you can pass this state to any other component which needs to use the text-field element ref using React context.

This will also allow you to pass only the text-field-element in the context without using .current every time you want to use it.

I've implemented this solution based on the sandbox you provided: https://codesandbox.io/s/so-68234884-xuru1?file=/src/App.js

However, for your use-case, this might be an overkill and you could just stick with calling .current whenever you use this ref.

Related