Course contentsShow
← React
Lesson 321 of 2,3969. Class Components (Legacy Overview)Free lesson

From Instance Variables to useRef

Convert class instance properties (this.x) that don't trigger renders to useRef for mutable values.

From Instance Variables to useRef

You'll learn how to replace class instance properties that don't trigger renders with useRef in functional components.

The Class Component Pattern

In class components, you could create instance variables — properties attached to this that held values but didn't trigger re-renders when changed:

class Timer extends React.Component {
  intervalId = null; // Instance variable
  
  componentDidMount() {
    this.intervalId = setInterval(() => {
      console.log('tick');
    }, 1000);
  }
  
  componentWillUnmount() {
    clearInterval(this.intervalId); // Access later
  }
}

Notice this.intervalId isn't in this.state. Changing it doesn't cause renders — it's just a "sticky note" that persists between renders.

The Functional Component Equivalent: useRef

In functional components, useRef serves this exact purpose:

function Timer() {
  const intervalId = useRef(null); // Mutable container
  
  useEffect(() => {
    intervalId.current = setInterval(() => {
      console.log('tick');
    }, 1000);
    
    return () => clearInterval(intervalId.current);
  }, []);
}

The key insight: useRef returns an object with a .current property you can read and write freely. Changing .current never triggers a re-render, just like instance variables.

When to Use useRef Over State

Use useRef when you need to remember something between renders but don't need React to re-render when it changes:

  • Timer IDs
  • Previous values for comparison
  • DOM references (covered later)
  • Any mutable value that's "behind the scenes"

Use useState when changing the value should update the UI.

Key Takeaway: Class instance variables (this.x) that don't trigger renders convert directly to useRef(x) — both create mutable containers that persist across renders without causing re-renders when changed.