Understanding useRef
and Mutable Refs in React with TypeScript
When working with React and TypeScript, useRef
is a useful hook that helps you interact with DOM elements and manage state without causing your component to re-render. In this blog , we’ll break down what useRef
and mutable refs are, when to use them, and walk through two examples to show how they work.
What is useRef
?
useRef
is a React hook that lets you create a reference to a DOM element or a value that stays the same between renders. This means you can update the value without triggering a re-render of the component.
In React, “refs” can refer to both DOM refs and mutable refs, but they are used in slightly different contexts.
Use Case 1: Focusing an Input Element
Imagine you want an input field to automatically get focus when the component loads. Here’s how you can do that with useRef
:
import { useEffect, useRef } from 'react';
const DomRef = () => {
//hold the reference value for input element with type
const inputRef = useRef<HTMLInputElement>(null);
//works on rendering
useEffect(() => {
inputRef.current?.focus();
}, []);
return (
<div>
//refer to inputRef
<input type='text' ref={inputRef} />
</div>
);
};
export default DomRef;
What’s happening here:
- Creating the Ref:
useRef
creates a reference to the input element, starting withnull
. - Focusing the Input: When the component mounts,
useEffect
runs and focuses the input if it’s there (inputRef.current?.focus()
). - Using the Ref: We connect
inputRef
to the input field with theref
attribute.
What are Mutable Refs?
Mutable refs are like normal refs but they can store a value that changes without causing a re-render. They’re great for things like timers, where you want to update the value without re-rendering the component.
Use Case 2: Creating a Timer
Here’s an example of using useRef
to manage a timer that counts up every second:
import { useEffect, useRef, useState } from 'react';
const MutableRef = () => {
//state stores and state changes then it re render
const [timer, setTimer] = useState<number>(0);
//ref will hold interval id without trigerring re render
const intervalRef = useRef<number | null>(null);
const stopTimer = () => {
if (intervalRef.current) window.clearInterval(intervalRef.current);
};
const startTimer = () => {
if (intervalRef.current) intervalRef.current = window.setInterval(() => setTimer(timer => timer + 1), 1000);
};
useEffect(() => {
intervalRef.current = window.setInterval(() => setTimer(timer => timer + 1), 1000);
return () => {
stopTimer();
};
}, []);
return (
<div>
Timer: {timer}
<button onClick={stopTimer}>Stop Timer</button>
<button onClick={startTimer}>Resume Timer</button>
</div>
);
};
export default MutableRef;
What’s happening here:
- State and Ref: We create a
timer
state and anintervalRef
to hold the timer’s ID. - Stopping the Timer:
stopTimer
clears the interval using the ID stored inintervalRef.current
. - Starting the Timer:
startTimer
sets a new interval to update the timer every second. - Setting up the Interval: When the component mounts,
useEffect
sets the interval and clears it when the component unmounts. - Control Buttons: Buttons call
stopTimer
andstartTimer
to control the timer.
When to Use Refs and Mutable Refs
Use refs when:
- You need to interact with a DOM element (like focusing an input).
- You want to store a value that stays the same between renders without causing re-renders.
Use mutable refs when:
- You need to store a changing value that doesn’t require a re-render (like timer IDs).
When you need to manipulate the DOM in ways that React’s declarative approach doesn’t cover, such as focusing an input, measuring the size of an element, or integrating with non-React libraries that require direct DOM manipulation.
Mutable refs are used to keep track of mutable values that need to persist across renders without triggering a re-render. These refs are often used for storing values like timers, interval IDs, or other values that should not cause the component to update when they change.
Key Differences
Purpose
DOM Refs: Used to access and interact with DOM elements.
Mutable Refs: Used to store mutable values that persist across renders without causing re-renders.
Usage Context:
DOM Refs: Typically assigned to the ref attribute of a JSX element.
Mutable Refs: Used to hold any mutable value, not necessarily linked to a DOM element.
Re-rendering:
DOM Refs: Do not cause re-renders when updated, since they are tied to DOM elements.
Mutable Refs: Do not cause re-renders when their values change, making them suitable for storing data that should persist without triggering updates.
Thanks Happy coding …. Share Follow