useRef
- React Native course
- Intermediate
- Lesson 4/116
- 5 min
Learn mutable references with useRef.
What is useRef?
useRef is a hook that holds a mutable reference. When you write const ref = useRef(0), ref.current starts as 0. You change it with ref.current = 5; this assignment does not trigger a re-render.
Two common uses: first, to access a DOM node or component (for example <TextInput ref={inputRef} />); second, to keep a value that should not trigger a re-render (for example a timer id). Import useRef from the react package: import { useRef } from "react";.
Access a TextInput with ref
In React Native you can access a TextInput through the ref attribute. You write const inputRef = useRef(null) and pass <TextInput ref={inputRef} />. Then you call inputRef.current.focus() to focus it programmatically.
This pattern is handy on form screens: when the user presses a button you can move focus to the next field automatically. ref.current starts as null; when the component mounts React assigns the node, and on unmount it sets it back to null.
Practice Hold a counter with useRef
Write a Counter component. Create countRef with useRef (initial value 0). When a button is pressed, increment countRef.current and log it with console.log. The component returns <Text>Counter</Text>.
Starter code
// Import useRef
function Counter() {
// Create a counter reference with useRef; initial value is 0
function handlePress() {
// Increment the reference value and log it
}
return <Text>Counter</Text>;
}Sample solution
import { useRef } from "react";
import { Text } from "react-native";
function Counter() {
const countRef = useRef(0);
function handlePress() {
countRef.current += 1;
console.log(countRef.current);
}
return <Text>Counter</Text>;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when ref.current changes?
const ref = useRef(0);
ref.current = 5;- The component re-renders
- The component is unmounted
- An error is thrown
- Nothing happens; no re-render is triggered Correct answer
Explanation: Assigning to useRef does not trigger a re-render.
2 Add the ref attribute
<TextInput ____={inputRef} placeholder="Ad" />
<TextInput ref={inputRef} placeholder="Ad" />
Explanation: The ref attribute binds the reference.
3 Match the concept to its role
| Term | Meaning |
|---|---|
useRef |
Mutable reference |
ref.current |
Held value |
null |
Initial value |
focus() |
Sets focus programmatically |