JavaScript and React course · Module 5: useEffect and Custom Hooks

References with useRef

13 min read ·
In this lesson8

On our cosmic journey through React, sometimes we need to maintain certain data or references to DOM elements that persist between renders but don't cause the component to re-render. The useRef hook is like a storage compartment on a spaceship - it lets you store important things that don't change with every maneuver of the ship.

What is useRef?

The useRef hook is one of the built-in hooks in React that:

  1. Creates a mutable reference field that survives throughout the entire component lifecycle
  2. Does not cause component re-rendering when its value changes
  3. Can be used to store references to DOM elements or any other values

Basic syntax:

const refContainer = useRef(initialValue);

The returned object refContainer has a .current property that is initialized with the initial value (initialValue). This value can be changed without triggering a re-render.

Main use cases for useRef

1. Accessing DOM elements

One of the most popular uses of useRef is gaining direct access to DOM nodes:

function SpaceshipControls() {
  // Creating reference
  const thrusterControlRef = useRef(null);

  // Function using reference to DOM element
  const focusThrusterControl = () => {
    // Access DOM element through .current property
    thrusterControlRef.current.focus();
  };

  return (
    <div className="control-panel">
      <h2>Thruster Control Panel</h2>

      {/* Attaching the ref to the input element */}
      <input
        ref={thrusterControlRef}
        type="range"
        min="0"
        max="100"
        className="thruster-slider"
      />

      <button onClick={focusThrusterControl}>
        Activate thrust control
      </button>
    </div>
  );
}

In this example:

  1. We create a reference thrusterControlRef using useRef(null)
  2. We assign this reference to the input element using the ref attribute
  3. We use the reference to call the focus() method on the DOM element

2. Storing mutable values between renders

useRef can also be used to store values that:

  • Should not cause a re-render when changed
  • Must remain stable throughout the component's lifecycle
function MissionTimer() {
  const [seconds, setSeconds] = useState(0);
  const timerIdRef = useRef(null);

  // Function to start the timer
  const startTimer = () => {
    if (timerIdRef.current !== null) return; // Avoid duplicate timers

    timerIdRef.current = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);
  };

  // Function to stop the timer
  const stopTimer = () => {
    clearInterval(timerIdRef.current);
    timerIdRef.current = null;
  };

  // Clean up interval on unmount
  useEffect(() => {
    return () => {
      if (timerIdRef.current !== null) {
        clearInterval(timerIdRef.current);
      }
    };
  }, []);

  return (
    <div className="mission-timer">
      <p>Mission time: {seconds} seconds</p>
      <button onClick={startTimer}>Start</button>
      <button onClick={stopTimer}>Stop</button>
    </div>
  );
}

In this example, we use useRef to store the interval ID. This is an ideal use case because:

  • We don't need a re-render when the interval ID changes
  • We need to preserve the ID between renders to be able to stop the interval
  • This value is not used directly in the rendered JSX

3. Tracking previous values

One interesting use of useRef is tracking previous values of props or state:

function usePrevious(value) {
  const ref = useRef();

  // Update ref.current after rendering
  useEffect(() => {
    ref.current = value;
  }, [value]);

  // Returns the previous value (undefined during the first render)
  return ref.current;
}

function AsteroidTracker({ asteroidId }) {
  const [asteroidData, setAsteroidData] = useState(null);
  // Track the previous ID
  const previousAsteroidId = usePrevious(asteroidId);

  // Effect that logs the change of the observed asteroid
  useEffect(() => {
    if (previousAsteroidId !== asteroidId) {
      console.log(`Tracking changed from asteroid ${previousAsteroidId} to ${asteroidId}`);
      // Here we could fetch new data about the asteroid
    }
  }, [asteroidId, previousAsteroidId]);

  // Rendering...
}

The usePrevious hook uses useRef to store the previous value. The reference is updated in useEffect, which runs after rendering, so the value stored in the ref is always one render cycle "behind" the current value.

4. Avoiding unnecessary effects

useRef can help with optimization by avoiding unnecessary effects:

function TelemetryMonitor({ shipId }) {
  const [data, setData] = useState(null);
  const [isConnected, setIsConnected] = useState(false);

  // Store the ID to avoid unnecessary connection changes
  const lastShipIdRef = useRef(shipId);

  useEffect(() => {
    // Check if the ship ID actually changed
    if (lastShipIdRef.current === shipId && isConnected) {
      console.log('Ship hasn't changed, skipping reconnection');
      return;
    }

    // Update ref with the new ID
    lastShipIdRef.current = shipId;

    // Establish connection...
    console.log(`Connecting to ship telemetry ${shipId}...`);

    const connection = telemetryService.connect(shipId);
    setIsConnected(true);

    connection.onData(newData => {
      setData(newData);
    });

    return () => {
      console.log(`Disconnecting ship telemetry ${shipId}...`);
      connection.disconnect();
      setIsConnected(false);
    };
  }, [shipId]);

  // Rendering...
}

useRef vs useState - when to use which?

The difference between useRef and useState is crucial to understand:

AspectuseRefuseState
Triggers re-renderNoYes
Preserves value between rendersYesYes
Accessing valueThrough the .current propertyDirectly by reading the state variable
Updating valueDirect mutation ref.current = newValueThrough updater function setState(newValue)
When to use?For values that don't affect render outputFor values that should trigger re-rendering

When to use useRef:

  • Accessing DOM elements
  • Storing timer and interval IDs
  • Storing previous values
  • Values that change frequently but don't affect UI
  • Storing class instances and objects that shouldn't be recreated on every render

When to use useState:

  • Data that affects what the user sees
  • Values whose changes should cause UI updates
  • State that controls the behavior or appearance of the user interface

Advanced useRef patterns

1. Callback Refs

Sometimes we need greater control over when a ref is assigned. In such cases, we can use a callback ref:

function SpectrumAnalyzer() {
  const [frequency, setFrequency] = useState(440);
  let canvasRef = useRef(null);

  // Callback function for ref, called when ref is assigned or detached
  const setCanvasRef = useCallback(element => {
    // element will be null during unmounting
    if (element) {
      canvasRef.current = element;
      // We can now perform initialization after the reference is assigned
      initializeCanvas(element, frequency);
    } else {
      // Cleaning up resources on unmount
      if (canvasRef.current) {
        cleanupCanvas(canvasRef.current);
      }
      canvasRef.current = null;
    }
  }, [frequency]); // Dependency on frequency

  // Function initializing canvas
  const initializeCanvas = (canvas, freq) => {
    console.log(`Initializing analyzer for frequency ${freq} Hz`);
    const ctx = canvas.getContext('2d');
    // Drawing...
  };

  return (
    <div>
      <canvas
        ref={setCanvasRef}
        width="600"
        height="300"
      />
      <input
        type="range"
        min="20"
        max="20000"
        value={frequency}
        onChange={e => setFrequency(Number(e.target.value))}
      />
      <div>Frequency: {frequency} Hz</div>
    </div>
  );
}

Callback ref gives us more control because it's called both when assigning and when removing the reference.

2. Combining useRef with forwardRef

Sometimes we want to pass a reference to a child component. We can do this using forwardRef:

// Child component
const NavigationControl = forwardRef((props, ref) => {
  return (
    <div className="nav-control">
      <label>{props.label}</label>
      <input
        ref={ref}
        type="text"
        className="nav-input"
        value={props.value}
        onChange={props.onChange}
      />
    </div>
  );
});

// Parent component
function NavigationPanel() {
  const destinationInputRef = useRef(null);
  const [destination, setDestination] = useState('');

  const focusDestination = () => {
    // We can access the inner input thanks to forwardRef
    destinationInputRef.current.focus();
  };

  return (
    <div className="nav-panel">
      <h2>Navigation Panel</h2>

      <NavigationControl
        ref={destinationInputRef}
        label="Destination:"
        value={destination}
        onChange={e => setDestination(e.target.value)}
      />

      <button onClick={focusDestination}>
        Set destination
      </button>
    </div>
  );
}

forwardRef allows a component to receive a reference from its parent and pass it to a specific element inside the component.

3. Storing multiple references

Sometimes we need to track multiple elements, for example a list of elements:

function StarMap({ stars }) {
  // Storing map of references to stars
  const starRefs = useRef({});

  // Function to scroll to a specific star
  const scrollToStar = (starId) => {
    if (starRefs.current[starId]) {
      starRefs.current[starId].scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
    }
  };

  return (
    <div className="star-map-container">
      <div className="star-list">
        {stars.map(star => (
          <div
            key={star.id}
            // We save the reference to the element in our map
            ref={el => starRefs.current[star.id] = el}
            className="star-item"
          >
            <h3>{star.name}</h3>
            <p>Typ: {star.type}</p>
            <p>Distance: {star.distance} light years</p>
          </div>
        ))}
      </div>

      <div className="star-navigator">
        <h3>Quick navigation</h3>
        {stars.map(star => (
          <button
            key={star.id}
            onClick={() => scrollToStar(star.id)}
          >
            {star.name}
          </button>
        ))}
      </div>
    </div>
  );
}

In this example, we store a map of references where the key is the star's id and the value is a reference to the corresponding DOM element.

Common pitfalls when using useRef

1. Attempting to render directly from ref.current

Since changing ref.current does not cause a re-render, attempting to use this value directly in JSX can lead to inconsistencies:

// BAD: Changing ref.current won't cause the interface to update
function BadCounter() {
  const countRef = useRef(0);

  const increment = () => {
    // This change will not cause a re-render
    countRef.current += 1;
    console.log(`Counter: ${countRef.current}`); // Will be logged correctly
  };

  return (
    <div>
      <p>Counter: {countRef.current}</p> {/* Won't update after clicking */}
      <button onClick={increment}>Increment</button>
    </div>
  );
}

// GOOD: Use useState for values that affect rendering
function GoodCounter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(c => c + 1);
  };

  return (
    <div>
      <p>Counter: {count}</p> {/* Will update after clicking */}
      <button onClick={increment}>Increment</button>
    </div>
  );
}

2. Forgetting about .current

A common mistake is forgetting to access the value through .current:

// BAD: Missing .current
function MissionLog({ onAddLog }) {
  const logInputRef = useRef(null);

  const handleAddLog = () => {
    // Error: We forgot about .current
    const logText = logInputRef.value;
    onAddLog(logText);
  };

  return (
    <div>
      <input ref={logInputRef} type="text" />
      <button onClick={handleAddLog}>Add entry</button>
    </div>
  );
}

// GOOD: We use .current
function MissionLog({ onAddLog }) {
  const logInputRef = useRef(null);

  const handleAddLog = () => {
    // Correct usage of .current
    const logText = logInputRef.current.value;
    onAddLog(logText);
    logInputRef.current.value = '';
  };

  return (
    <div>
      <input ref={logInputRef} type="text" />
      <button onClick={handleAddLog}>Add entry</button>
    </div>
  );
}

3. Improper use of ref for render control

useRef is not the appropriate tool for controlling when a component should render:

// BAD: Attempting to use ref to control rendering
function BadRenderControl() {
  const shouldUpdateRef = useRef(false);

  const forceUpdate = () => {
    shouldUpdateRef.current = true;
    // Missing mechanism to force re-rendering
  };

  console.log('Rendering',shouldUpdateRef.current);

  // This won't work as expected
  if (shouldUpdateRef.current) {
    shouldUpdateRef.current = false;
    // Some operations...
  }

  return <button onClick={forceUpdate}>Refresh</button>;
}

// GOOD: Using useState to control rendering
function GoodRenderControl() {
  const [update, setUpdate] = useState(0);
  const didUpdateRef = useRef(false);

  const forceUpdate = () => {
    setUpdate(u => u + 1); // Triggers re-rendering
  };

  console.log('Rendering',update);

  useEffect(() => {
    if (update > 0) {
      didUpdateRef.current = true;
      // Operations after update...
    }
  }, [update]);

  return <button onClick={forceUpdate}>Refresh</button>;
}

Best practices with useRef

  1. Use useRef for values that don't affect rendering - if a value change should cause an interface update, use useState.

  2. Be cautious with direct DOM manipulation - DOM manipulation through references should be limited and well thought out.

  3. Initialize refs with appropriate initial values - for example null for DOM references or initial values for counters.

  4. Check if ref.current exists before using it - especially for DOM references that may be null during the first render.

  5. Use useCallback for ref-creating functions - if you're passing a reference function, consider wrapping it in useCallback for optimization.

  6. Avoid overusing refs - although refs are useful, over-relying on them can lead to hard-to-maintain code.

Practical example: Advanced mission video player

Below is a more complex example that demonstrates various aspects of using useRef:

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

function MissionVideoPlayer({ videoUrl, onProgress }) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [volume, setVolume] = useState(0.7);

  // References
  const videoRef = useRef(null);          // Reference to video element
  const progressBarRef = useRef(null);    // Reference to progress bar
  const animationFrameRef = useRef(null); // requestAnimationFrame ID for updating time
  const isMountedRef = useRef(true);      // Flag indicating whether the component is mounted
  const lastUpdateTimeRef = useRef(0);    // Time of the last update for throttling

  // Function initializing video metadata
  const handleLoadedMetadata = () => {
    if (videoRef.current) {
      setDuration(videoRef.current.duration);
      videoRef.current.volume = volume;
    }
  };

  // Function updating progress bar
  const updateProgressBar = useCallback(() => {
    if (!videoRef.current || !isMountedRef.current) return;

    const now = Date.now();
    if (now - lastUpdateTimeRef.current > 200) { // Throttling to 5 updates per second
      setCurrentTime(videoRef.current.currentTime);
      onProgress(videoRef.current.currentTime);
      lastUpdateTimeRef.current = now;
    }

    // Continue updating if video is playing
    if (videoRef.current.paused) return;
    animationFrameRef.current = requestAnimationFrame(updateProgressBar);
  }, [onProgress]);

  // Start or pause playback
  const togglePlayPause = () => {
    if (!videoRef.current) return;

    if (videoRef.current.paused) {
      videoRef.current.play();
      setIsPlaying(true);
      animationFrameRef.current = requestAnimationFrame(updateProgressBar);
    } else {
      videoRef.current.pause();
      setIsPlaying(false);
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
    }
  };

  // Changing playback position after clicking progress bar
  const handleProgressBarClick = (e) => {
    if (!progressBarRef.current || !videoRef.current) return;

    const rect = progressBarRef.current.getBoundingClientRect();
    const position = (e.clientX - rect.left) / rect.width;
    const newTime = duration * Math.max(0, Math.min(1, position));

    videoRef.current.currentTime = newTime;
    setCurrentTime(newTime);
  };

  // Changing volume
  const handleVolumeChange = (e) => {
    const newVolume = parseFloat(e.target.value);
    setVolume(newVolume);

    if (videoRef.current) {
      videoRef.current.volume = newVolume;
    }
  };

  // Effect cleaning up animationFrame and setting mounting flag
  useEffect(() => {
    return () => {
      isMountedRef.current = false;
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current);
      }
    };
  }, []);

  // Formatting time (mm:ss)
  const formatTime = (timeInSeconds) => {
    const minutes = Math.floor(timeInSeconds / 60);
    const seconds = Math.floor(timeInSeconds % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  return (
    <div className="mission-video-player">
      <video
        ref={videoRef}
        src={videoUrl}
        onLoadedMetadata={handleLoadedMetadata}
        onEnded={() => setIsPlaying(false)}
      />

      <div className="controls">
        <button onClick={togglePlayPause}>
          {isPlaying ? 'Pause' : 'Play'}
        </button>

        <div className="time-display">
          {formatTime(currentTime)} / {formatTime(duration)}
        </div>

        <div
          ref={progressBarRef}
          className="progress-bar"
          onClick={handleProgressBarClick}
        >
          <div
            className="progress-fill"
            style={{ width: `${(currentTime / duration) * 100}%` }}
          />
        </div>

        <div className="volume-control">
          <label>Volume:</label>
          <input
            type="range"
            min="0"
            max="1"
            step="0.05"
            value={volume}
            onChange={handleVolumeChange}
          />
        </div>
      </div>
    </div>
  );
}

This example demonstrates several advanced aspects of working with useRef:

  1. Multiple different uses of references:

    • Access to DOM element (videoRef, progressBarRef)
    • Storing animation ID (animationFrameRef)
    • Mounting flag (isMountedRef)
    • Tracking values for throttling (lastUpdateTimeRef)
  2. Integration of references with effects and callbacks

  3. Direct manipulation of the video element through its API

  4. Throttling state updates using time references

Summary

The useRef hook is an essential tool in the React toolkit, particularly useful for:

  • Storing references to DOM elements
  • Maintaining values between renders without triggering re-rendering
  • Tracking previous values
  • Storing timer, interval, and requestAnimationFrame IDs
  • Storing flags and values that don't directly affect the interface

The key to effectively using useRef is understanding when to use it instead of useState. The fundamental difference is that useRef does not cause a re-render when its value changes, making it the ideal choice for operations that shouldn't affect the rendering cycle.

On our cosmic journey through React, useRef is like a storage compartment on the ship - a place where you can store things you need to have on hand, but that don't require the attention of the entire crew every time they change.

Code for this lesson: App.jsx
import React, { useState, useRef, useEffect } from 'react';

// useRef for storing references to DOM elements
function DOMReferenceDemo() {
  const inputRef = useRef(null);
  const canvasRef = useRef(null);

  const focusInput = () => {
    inputRef.current?.focus();
  };

  const drawOnCanvas = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Drawing stars
    for (let i = 0; i < 50; i++) {
      const x = Math.random() * canvas.width;
      const y = Math.random() * canvas.height;
      const radius = Math.random() * 2;

      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(255, 255, 255, ${Math.random()})`;
      ctx.fill();
    }

    // Drawing a planet
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height / 2, 30, 0, Math.PI * 2);
    ctx.fillStyle = '#61dafb';
    ctx.fill();
  };

  return (
    <div className="demo-card">
      <h2>DOM References</h2>

      <div className="input-section">
        <input ref={inputRef} type="text" placeholder="Click the button below" />
        <button onClick={focusInput}>Focus the input</button>
      </div>

      <div className="canvas-section">
        <canvas ref={canvasRef} width={280} height={150} />
        <button onClick={drawOnCanvas}>Draw space</button>
      </div>
    </div>
  );
}

// useRef for storing values between renders
function PreviousValueDemo() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef(0);

  useEffect(() => {
    prevCountRef.current = count;
  });

  return (
    <div className="demo-card">
      <h2>Previous value</h2>
      <div className="values">
        <div className="value-box">
          <span className="label">Current:</span>
          <span className="number current">{count}</span>
        </div>
        <div className="value-box">
          <span className="label">Previous:</span>
          <span className="number previous">{prevCountRef.current}</span>
        </div>
      </div>
      <button onClick={() => setCount(c => c + 1)}>Increase</button>
    </div>
  );
}

// useRef for measuring elements
function MeasurementDemo() {
  const boxRef = useRef(null);
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
  const [boxSize, setBoxSize] = useState(100);

  const measureBox = () => {
    if (boxRef.current) {
      const rect = boxRef.current.getBoundingClientRect();
      setDimensions({ width: rect.width, height: rect.height });
    }
  };

  return (
    <div className="demo-card">
      <h2>Element measurements</h2>
      <div
        ref={boxRef}
        className="measure-box"
        style={{ width: boxSize, height: boxSize }}
      >
        {boxSize}x{boxSize}
      </div>
      <div className="measurement-info">
        Measured: {dimensions.width.toFixed(0)} x {dimensions.height.toFixed(0)}
      </div>
      <div className="controls">
        <button onClick={() => setBoxSize(s => Math.max(50, s - 20))}></button>
        <button onClick={measureBox}>Measure</button>
        <button onClick={() => setBoxSize(s => Math.min(200, s + 20))}></button>
      </div>
    </div>
  );
}

// useRef for storing timeouts/intervals
function TimerRefDemo() {
  const [time, setTime] = useState(0);
  const [isRunning, setIsRunning] = useState(false);
  const intervalRef = useRef(null);

  const start = () => {
    if (intervalRef.current) return;

    setIsRunning(true);
    intervalRef.current = setInterval(() => {
      setTime(t => t + 1);
    }, 100);
  };

  const stop = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    setIsRunning(false);
  };

  const reset = () => {
    stop();
    setTime(0);
  };

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  const formatTime = (t) => {
    const seconds = Math.floor(t / 10);
    const decimals = t % 10;
    return `${seconds}.${decimals}s`;
  };

  return (
    <div className="demo-card">
      <h2>⏱Timer with useRef</h2>
      <div className="timer-display">{formatTime(time)}</div>
      <div className="controls">
        <button onClick={start} disabled={isRunning}>▶Start</button>
        <button onClick={stop} disabled={!isRunning}>⏸Pause</button>
        <button onClick={reset}>Reset</button>
      </div>
      <p className="hint">Interval ID stored in useRef</p>
    </div>
  );
}

function App() {
  return (
    <div className="app">
      <h1>useRef Hook</h1>
      <p className="subtitle">References and values outside the render cycle</p>
      <div className="demos">
        <DOMReferenceDemo />
        <PreviousValueDemo />
        <MeasurementDemo />
        <TimerRefDemo />
      </div>
    </div>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the dependency array in useEffect contain?

  2. 2. Which of the following is an example of a side effect in React?

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the useRef declaration elements from left to right:

  • Vertical ordering

    Order the steps for correctly using async/await inside useEffect:

  • Click in order

    Arrange async operations in useEffect:

  • Code editor

    Geolocation Position Tracking

  1. QuestionDependency Array in useEffect
  2. QuestionSide Effects in React
  3. Put in orderuseRef Syntax
  4. Put in orderAsync Pattern in useEffect
  5. Click in orderAsync Operations in useEffect
  6. Coding taskPractice: Geolocation API

Useful articles