JAVASCRIPT

Persist Mutable Values Without Re-renders Using useRef

Utilize the useRef hook in React to store mutable values that persist across renders without triggering component updates, ideal for timers or direct DOM element references.

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

function TimerComponent() {
  const intervalRef = useRef(null); // Stores a mutable value that doesn't trigger re-renders
  const [count, setCount] = useState(0); // Triggers re-renders

  const startTimer = () => {
    if (!intervalRef.current) {
      intervalRef.current = setInterval(() => {
        setCount(prevCount => prevCount + 1);
      }, 1000);
    }
  };

  const stopTimer = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  };

  useEffect(() => {
    // Cleanup on unmount
    return () => stopTimer();
  }, []);

  return (
    <div>
      <h1>Timer: {count}s</h1>
      <button onClick={startTimer}>Start Timer</button>
      <button onClick={stopTimer}>Stop Timer</button>
      <p>The internal `intervalRef` value changes without causing the component to re-render, while `count` updates do.</p>
    </div>
  );
}

export default TimerComponent;
How it works: The `useRef` hook returns a mutable ref object whose `.current` property is initialized to the passed argument (`initialValue`). The returned object will persist for the full lifetime of the component. Unlike `useState`, updating a ref's `.current` property does not trigger a component re-render. This makes `useRef` perfect for storing mutable values that need to persist across renders (like a timer ID, a previous state value, or a direct reference to a DOM element) without causing the component to update itself.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs