0
0
ReactHow-ToBeginner · 3 min read

How to Store Previous Value Using useRef in React

In React, you can store the previous value by using the useRef hook to keep a mutable reference that persists across renders without triggering updates. Update the ref.current inside a useEffect after rendering to save the latest value for the next render.
📐

Syntax

The useRef hook creates a mutable object with a current property that you can update without causing the component to re-render. You typically initialize it with null or the initial value.

Use useEffect to update the ref.current after each render to keep track of the previous value.

javascript
const refContainer = useRef(initialValue);

useEffect(() => {
  refContainer.current = valueToTrack;
}, [valueToTrack]);
💻

Example

This example shows a counter that displays its current and previous count values. The previous count is stored using useRef and updated after each render.

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

function PreviousValueExample() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef(null);

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

  const prevCount = prevCountRef.current;

  return (
    <div>
      <p>Current count: {count}</p>
      <p>Previous count: {prevCount !== null ? prevCount : 'None'}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default PreviousValueExample;
Output
Current count: 0 Previous count: None (After clicking Increment button) Current count: 1 Previous count: 0
⚠️

Common Pitfalls

  • Trying to store previous value in state causes extra renders and can lead to infinite loops.
  • Not updating ref.current inside useEffect causes the previous value to never change.
  • Accessing ref.current before it is set may return null or undefined, so handle initial cases.
javascript
/* Wrong way: updating state to store previous value causes re-render loop */

const [prev, setPrev] = useState(null);

useEffect(() => {
  setPrev(currentValue); // This triggers re-render every time
}, [currentValue]);

/* Right way: useRef to store previous value without re-render */
const prevRef = useRef(null);

useEffect(() => {
  prevRef.current = currentValue;
}, [currentValue]);
📊

Quick Reference

  • useRef(initialValue): creates a mutable ref object.
  • ref.current: holds the stored value.
  • Update ref.current inside useEffect to track previous value.
  • Access ref.current to get the previous value during render.

Key Takeaways

Use useRef to store previous values without causing re-renders.
Update ref.current inside useEffect after each render to save the latest value.
Avoid using state to track previous values to prevent infinite render loops.
Handle initial render where previous value may be null or undefined.
Access the previous value via ref.current during rendering.