← Back to Chapters

useRef Hook

? useRef Hook

? Quick Overview

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.

? Key Concepts

  • Does not trigger re-render when value changes
  • Value persists across renders
  • Commonly used for accessing component methods (focus(), scrollTo())
  • Useful alternative to instance variables

? Syntax / Theory

The useRef hook returns an object with a single property .current. This property can hold any mutable value.

? View Code Example
// Import useRef from react
import { useRef } from "react";

// Create a ref with initial value
const myRef = useRef(null);

? Code Example(s)

? View Code Example: Focus Input
// 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>
  );
}

? Live Output / Explanation

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.

? Interactive / Visual Explanation

? React Native Simulator

Explore two common use cases below:
1. Focusing an input.
2. Scrolling a view programmatically.

My Native App
Use Case 1: inputRef.current.focus()
Use Case 2: scrollRef.current.scrollTo()

Scroll down to see the button!

 
Action Triggered
 

? Use Cases

  • Accessing TextInput (focus/blur)
  • Controlling ScrollView (scrollTo, scrollToEnd)
  • Storing previous state/props for comparison
  • Managing intervals and timers (clearTimeout)

? Tips & Best Practices

  • Use useRef when you don’t need UI updates.
  • Avoid using refs for data flow; use props/state instead.
  • Ref updates happen synchronously but don't trigger effects immediately.

? Try It Yourself

  • Create a stopwatch where the interval ID is stored in a ref.
  • Build a form that focuses the next input when "Next" is pressed.
  • Create a "Scroll to Bottom" chat interface using useRef.