useRef is a React Hook used to create a mutable reference that persists across renders. In React Native, it is commonly used to access components (like TextInputs or ScrollViews), store mutable values, and avoid unnecessary re-renders.
focus(), scrollTo())The useRef hook returns an object with a single property .current. This property can hold any mutable value.
// Import useRef from react
import { useRef } from "react";
// Create a ref with initial value
const myRef = useRef(null);
// Example: Focus a TextInput using useRef
import React, { useRef } from "react";
import { View, TextInput, Button } from "react-native";
export default function App() {
const inputRef = useRef(null);
return (
<View>
<TextInput ref={inputRef} placeholder="Enter text" />
<Button
title="Focus Input"
onPress={() => inputRef.current.focus()}
/>
</View>
);
}
When the button is pressed, the TextInput automatically gains focus. This happens because useRef provides direct access to the underlying native component without triggering a re-render.
Explore two common use cases below:
1. Focusing an input.
2. Scrolling a view programmatically.
Scroll down to see the button!
useRef when you don’t need UI updates.useRef.