useRef
useRef
is a hook that allows a component to maintain a mutable reference that doesn't trigger a re-render when updated. It returns an instance of Ref
which has a single mutable value
property, which should only be read/written on the UI thread.
To familiarize yourself with the concept and rules for hooks, see the Introduction to Hooks page.
Managing UI Thread State with useRef
β
Ref.value should only be read/written from the main thread. Since there is no guarantee that a component's render
function is executed on the main thread, it should not be accessed during the execution of render
.
Some locations where it is safe to access and mutate Ref.value
:
onClick
and other View events.onVisible
and other visibility events.useEffect
and its cleanup lambda.
Appropriate use cases of useRef
are best shown by example. Note that none of these examples read or write useRef
off the main thread or during the execution of the main body of the component's render
function.
Example: Logging Seen Stateβ
In the code below, useRef
is used to track whether we've handled the onVisible
event previously. Updating hasLoggedVisible.value
to true
doesn't trigger a re-render, unlike storing and updating it via useState
.
class LogOnceComponent : KComponent() {
override fun ComponentScope.render(): Component {
val hasLoggedVisible = useRef<Boolean> { false }
return Text(
style =
Style.onVisible {
// onVisible executes on the main thread, so it's safe to read/write hasLoggedVisible
if (!hasLoggedVisible.value) {
doLogVisible(androidContext)
hasLoggedVisible.value = true
}
},
text = "I'll let you know when I'm visible, but only once!")
}
}
Pairing with useEffect
β
Pairing useRef
with useEffect
is a common pattern. When you need to make objects created in useEffect
, available outside of its lambda, you can store them using useRef
. For more information on useEffect
, see the code samples in the useEffect page.