Skip to main content
TOPIC 3 OF 8 · 2 MIN READ

Managing State with useRef

The `useRef` hook provides a way to persist a value or reference across renders without causing the component to re-render when the value changes.

Key concepts

useRef

A hook that provides a way to persist a value or reference across renders without causing the component to re-render when the value changes.

Step by step

Use Cases:

  • DOM Manipulation: Access and manipulate DOM elements directly.
  • Persisting Values: Store mutable values like timers or counters that don't trigger re-renders.
  • Performance Optimization: Avoid unnecessary updates by persisting values outside of the component's state.

When Not to Use useRef:

  • State-Driven Logic: If the data affects rendering, use `useState` instead.
  • Complex State: For complex state transitions, use `useReducer`.

Examples

DOM Manipulation:

import React, { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current.focus(); // Access the DOM element directly
  };

  return (
    <div>
      <input ref={inputRef} placeholder="Type here..." />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

Persisting a Timer:

import React, { useState, useRef } from 'react';

function Timer() {
  const [count, setCount] = useState(0);
  const timerRef = useRef(null);

  const startTimer = () => {
    timerRef.current = setInterval(() => setCount((prev) => prev + 1), 1000);
  };

  const stopTimer = () => {
    clearInterval(timerRef.current);
  };

  return (
    <div>
      <p>Timer: {count}</p>
      <button onClick={startTimer}>Start</button>
      <button onClick={stopTimer}>Stop</button>
    </div>
  );
}

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus