useRef for DOM Nodes and Mutable Values
Use useRef to hold a reference to a TextInput and programmatically focus it, and store a mutable value that persists across renders without triggering re-renders.
What is useRef?
useRef is a React hook that returns a mutable ref object whose .current property persists across renders. Unlike state variables, updating ref.current does not trigger a re-render. This makes useRef perfect for storing values that change frequently but should not cause the component to update.
import { useRef } from 'react';
function MyComponent() {
const myRef = useRef(null);
// myRef.current starts as null
// myRef.current persists across re-renders without triggering them
}Attaching a Ref to a Native Component
Pass a ref to a native component via its ref prop. React Native then populates ref.current with the underlying native component instance. This gives you access to methods like focus(), blur(), and measure() that are defined on the native component.
import { TextInput, Button, View } from 'react-native';
import { useRef } from 'react';
function SearchForm() {
const inputRef = useRef(null);
return (
<View>
<TextInput ref={inputRef} placeholder='Search...' />
<Button
title='Focus Input'
onPress={() => inputRef.current?.focus()}
/>
</View>
);
}All lessons in this course
- useRef for DOM Nodes and Mutable Values
- useReducer for Complex State Logic
- useCallback and useMemo for Performance
- Writing Custom Hooks