'React custom hooks: returning a ref from hook vs passing the ref as hooks argument
Consider I have a custom hook that uses one or more refs to DOM elements, I see two distinct ways how to write/use a hook like that (and I know there are probably even more nuances – e. g. callback refs).
Option 1: return a ref from custom hook and use it in a component:
const Option1 = () => {
const hooksRef = myCustomHookReturninARef()
return <div ref={hooksRef}>Using returned ref as prop.</div>
}
Option 2: create a ref in a component and pass it to a custom hook:
const Option2 = () => {
const componentsRef = React.createRef()
myCustomHookExpectingRefArgument(componentsRef)
return <div ref={componentsRef}>Using created ref as prop..</div>
}
I've been using either options and they both seems to be working fine. I know this is likely an opinionated question, but:
Are there some significant drawbacks using the first vs the second approach?
Solution 1:[1]
not an React virtuoso, but from my perspective the only drawback using Option1 is that you have to validate the returned value to be a ref, from computing perspective there is no difference
Solution 2:[2]
I came here because I myself have the same dilemma :-). My 2 cents:
- The hook user can be made more concise if the hook returns the ref since don't have to create it.
- On the other hand, if the user already have a ref from a different ref-returning hook, they might have to combine two different refs. While that's maybe a straightforward task, it certainly tripped me up when I was in that situation.
Maybe one could get the best of both worlds, by both receiving and returning a ref? If the hook doesn't get a ref then it simply creates one. Either way it can return the ref.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | syduki |
| Solution 2 | ukrutt |
