I've been using useRef in my function components as an alternative to class instance variables and I really like it. So typically it goes something like this:
First declare the variable, scrollRef
for example:
const scrollRef = useRef()
Then, assign the value of some ref to scrollRef.current
:
<ScrollView ref={ref => { scrollRef.current = ref }}>
// (Yeah, I'm doing mostly React Native)
Finally, use the ref:
<TouchableOpacity onPress={() => scrollRef.current.scrollToEnd()} />
This works fine. But when I have a lot of useRef
s it seems like I have two problems:
.current
is all over the place- there are some tricky cases and confusion when passing refs between components, when we're not immediately sure if we should read the value directly or read the
.current
key.
So I'm wondering if there is a better way.
I thought of declaring the variable with let
instead of const
, and then directly assign to .current
:
let myRef = useRef().current
And then directly reading and mutating myRef
What are the drawbacks of this, are there cases where this would not work? Are there any better solutions to avoid using .current
all over the place?