Hello! Welcome to the final lesson in our module on advanced state, context, and refs.
In our previous lesson, we explored the first major use case for useRef: gaining direct, imperative access to DOM elements. We learned that the key feature of useRef is that it returns a mutable object whose .current property can be changed without triggering a re-render.
Today, we'll dive into the second, equally important use case that this feature enables. Our goal is to learn how to use useRef to store mutable values that persist across renders without causing a re-render. This turns useRef into a powerful tool for managing data that a component needs to keep track of but doesn't directly display in its output. For someone with your background, you can think of this as creating an "instance variable" for a functional component.
Let's get started.
The Problem with State: The Infinite Re-render Loop
Imagine you want to build a simple component that counts and displays how many times it has been rendered. Given what we know so far, your first instinct might be to use useState and useEffect.
A naive attempt might look like this:
import { useState, useEffect } from 'react';
function RenderCounter() {
const [renderCount, setRenderCount] = useState(0);
useEffect(() => {
// Every time the component renders, increment the count
setRenderCount(prevCount => prevCount + 1);
});
return <div>I have rendered {renderCount} times.</div>;
}
What do you think happens here?
- The component renders.
useEffectruns after the render.setRenderCountis called, updating the state.- Updating state triggers a re-render.
- The component re-renders.
useEffectruns again... and we're caught in an infinite loop.
This is a classic problem that perfectly illustrates why we need a way to store information that persists across renders without triggering those renders. This is exactly what useRef is designed for.
This video provides an excellent side-by-side comparison of trying to solve this render-counting problem with useState versus useRef.
Please watch from 01:05 to 04:50. The video clearly explains why useState causes an infinite loop and then demonstrates how useRef elegantly solves the problem.
The Solution: The Mutable, Non-Rendering Ref
As the video demonstrated, useRef provides the solution. Let's look at the correct implementation:
import { useState, useRef, useEffect } from 'react';
function App() {
const [name, setName] = useState('');
// 1. Initialize a ref with a starting value of 0.
const renderCount = useRef(0);
useEffect(() => {
// 2. Mutate the .current property. This does NOT cause a re-render.
renderCount.current = renderCount.current + 1;
});
// Note: We display renderCount.current here for demonstration,
// but it won't update the screen until another render is triggered (e.g., by typing in the input).
return (
<>
<input value={name} onChange={e => setName(e.target.value)} />
<div>My name is {name}</div>
<div>I have rendered {renderCount.current} times</div>
</>
);
}
The key difference is that assigning a new value to renderCount.current is a simple mutation of a JavaScript object property. React's rendering engine doesn't track changes to ref objects, so no re-render is triggered, and the infinite loop is avoided.

useRef Typing: MutableRefObject
In the last lesson, when using useRef for DOM elements, the type was inferred as React.RefObject<T>. This type represents a read-only ref, as React is the one responsible for setting its .current property to the DOM node.
For today's use case, where we are the ones mutating the .current property, we use a different type: React.MutableRefObject<T>.
⚛️ Demystifying React's Types: Ref types
This article clearly distinguishes between the ref types in TypeScript, focusing on the MutableRefObject that is central to our current lesson.
Please read section '2️⃣ React.MutableRefObject'. It shows how to type a ref that you intend to modify yourself, like a counter.
When you initialize useRef with a non-null value, TypeScript correctly infers its type as React.MutableRefObject<T>.
// TypeScript infers this as React.MutableRefObject<number>
const counterRef = useRef(0);
// We can safely mutate .current
counterRef.current++;
Practical Use Cases for Mutable Refs
Beyond just counting renders, this pattern is useful in many real-world scenarios.
1. Managing Timer IDs
A very common use case is managing IDs from setInterval or setTimeout. You need to store the ID so you can clear it later, but you don't want to trigger a re-render every time you set or clear an interval.
useRef Hook // Simply Explained and Compared to useState
Let's watch a practical demonstration of building a timer component. This video shows how useRef is used to store the interval ID, while useState is used for the time value that needs to be displayed.
Watch from 05:51 to 07:21. Pay attention to how the intervalRef is used to hold the ID returned by setInterval and is later accessed to call clearInterval.
Here is a full implementation of that pattern:
import React, { useState, useRef, useEffect } from 'react';
function Stopwatch() {
const [seconds, setSeconds] = useState(0);
// Ref to hold the interval ID. Its type is inferred as MutableRefObject<number | undefined>
const intervalRef = useRef<NodeJS.Timeout>();
const handleStart = () => {
// Prevent multiple intervals from running
if (intervalRef.current) return;
intervalRef.current = setInterval(() => {
// Use functional update form for state
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);
};
const handleStop = () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = undefined; // Clean up the ref
}
};
const handleReset = () => {
handleStop();
setSeconds(0);
};
// Cleanup effect to stop the timer when the component unmounts
useEffect(() => {
return () => handleStop();
}, []);
return (
<div>
<h1>Time: {seconds}s</h1>
<button onClick={handleStart}>Start</button>
<button onClick={handleStop}>Stop</button>
<button onClick={handleReset}>Reset</button>
</div>
);
}
2. Storing the Previous Value of State or Props
Another powerful pattern is using a ref to track the previous value of a piece of state or a prop. This is useful in useEffect when you need to compare the current value to the previous one to decide if some action should be taken.
This part of the 'Learn useRef' video demonstrates this exact pattern: storing the previous value of a state variable.
Watch from 08:03 to 10:04. The key insight is understanding the timing: the useEffect hook runs after the render, making it the perfect place to update the ref with the value that was just rendered.
Here's how that logic works in code:
import React, { useState, useEffect, useRef } from 'react';
function ValueTracker({ value }: { value: number }) {
// Ref to store the previous value
const prevValueRef = useRef<number>();
useEffect(() => {
// This effect runs AFTER the component has rendered with the new `value`.
// So, we update the ref with the current value, which will be the "previous"
// value on the *next* render.
prevValueRef.current = value;
}, [value]); // The effect re-runs only when `value` changes
const previousValue = prevValueRef.current;
return (
<div>
<p>Current Value: {value}</p>
<p>Previous Value: {previousValue === undefined ? 'N/A' : previousValue}</p>
</div>
);
}
The render cycle and effect execution order is what makes this work:
- Component renders with new
value. It readsprevValueRef.current(which still holds the old value). - The UI is painted on the screen.
useEffectruns. It updatesprevValueRef.currentto the newvalue.- The ref now holds the "previous" value, ready for the next render.
Test your understanding!
You are building a component that receives a numeric score as a prop. You need to display the score and also display how much the score has changed since the last render (the "delta"). For example, if the score was 100 and becomes 120, you should display "Current Score: 120 (Change: +20)".
How would you implement this using useState and useRef?
Show answer
You would use a ref to store the previous score. The current score comes directly from props. The delta can be calculated during the render.
import React, { useRef, useEffect } from 'react';
function ScoreDisplay({ score }: { score: number }) {
const prevScoreRef = useRef<number>();
useEffect(() => {
// Update the previous score after each render where score changes
prevScoreRef.current = score;
}, [score]);
const prevScore = prevScoreRef.current;
// Calculate delta, handle the first render case where prevScore is undefined
const delta = prevScore !== undefined ? score - prevScore : 0;
// Format the delta with a sign
const deltaString = delta > 0 ? `+${delta}` : delta;
return (
<div>
Current Score: {score}
{prevScore !== undefined && ` (Change: ${deltaString})`}
</div>
);
}
The Golden Rule: Don't Read or Write Refs During Render
Finally, it's crucial to remember a fundamental rule for using refs.
The official React documentation is very clear about this. Let's read the 'Pitfall' section to understand this important constraint.
Read the section titled 'Pitfall: Do not write or read ref.current during rendering.' This explains why doing so makes your component's behavior unpredictable and impure.
As the docs state, React expects component bodies to be pure functions. This means for the same props and state, they should always return the same JSX. Reading from or writing to a mutable ref during the render phase breaks this rule.
- Writing during render is a side effect.
- Reading during render means your component's output now depends on something other than props and state, making it impure.
Always modify refs inside event handlers or useEffect hooks.
Conclusion
You have now mastered both primary uses of the useRef hook. While its most visible application is for DOM manipulation, its ability to act as a persistent, mutable container without causing re-renders is a fundamental tool for managing complex component logic.
Key Takeaways:
useRefcan store any mutable value that needs to persist across component renders.- The most important feature is that mutating
ref.currentdoes not trigger a re-render. - This makes
useRefthe perfect tool for storing "instance-like" variables such as timer IDs, previous state/prop values, or any other data that isn't directly used for rendering. - When used for this purpose, the ref's type is typically
React.MutableRefObject<T>. - The golden rule is to only read or write
ref.currentinside event handlers oruseEffecthooks, not during the render body itself.
Preview of the Next Module:
This lesson concludes our module on advanced state management. You've learned to handle global state with Context, manage complex transitions with useReducer, and break out of the declarative model with useRef.
Our next module, Module 7: Performance Optimization Techniques, builds directly on these concepts. Avoiding unnecessary re-renders with useRef is a form of performance optimization. We will now explore a suite of dedicated hooks and techniques—React.memo, useMemo, and useCallback—designed specifically to help you analyze and optimize your application's performance by preventing needless computations and re-renders.