0
0
ReactHow-ToBeginner · 3 min read

How to Create usePrevious Hook in React: Simple Guide

Create a usePrevious hook in React by using useRef to store the previous value and useEffect to update it after each render. This hook returns the value from the previous render, helping you compare past and current states or props.
📐

Syntax

The usePrevious hook uses useRef to keep a mutable reference that persists across renders without causing re-renders. useEffect updates this reference after each render with the current value, so the hook returns the previous value on the next render.

  • value: The current value you want to track.
  • ref.current: Stores the previous value.
  • useEffect: Updates ref.current after render.
javascript
import { useEffect, useRef } from 'react';

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}
💻

Example

This example shows a counter that displays its current and previous values using the usePrevious hook. Each time you click the button, the counter increases and the previous count is shown below.

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

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}

export default function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  return (
    <div style={{ fontFamily: 'Arial', padding: '1rem' }}>
      <h2>Current count: {count}</h2>
      <h3>Previous count: {prevCount === undefined ? 'None' : prevCount}</h3>
      <button onClick={() => setCount(count + 1)} aria-label="Increment count">
        Increment
      </button>
    </div>
  );
}
Output
Current count: 0 Previous count: None (After clicking Increment button) Current count: 1 Previous count: 0
⚠️

Common Pitfalls

Common mistakes when creating usePrevious include:

  • Not using useRef, which causes re-renders if you use useState instead.
  • Updating the ref inside the render body instead of inside useEffect, which breaks React's render cycle.
  • Forgetting to include the value in the useEffect dependency array, so the ref doesn't update correctly.
javascript
import { useRef, useEffect } from 'react';

// Wrong: updating ref during render
function usePreviousWrong(value) {
  const ref = useRef();
  ref.current = value; // This runs every render, not recommended
  return ref.current;
}

// Right: update ref inside useEffect
function usePreviousRight(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}
📊

Quick Reference

usePrevious Hook Cheat Sheet:

  • useRef() stores mutable value without re-render.
  • useEffect(() => { ref.current = value; }, [value]) updates ref after render.
  • Returns ref.current which holds previous value.
  • Use to compare previous and current props or state.

Key Takeaways

Use useRef to store previous value without causing re-renders.
Update the ref inside useEffect to keep it in sync after each render.
Return the ref's current value to get the previous render's value.
Avoid updating refs directly during render to prevent bugs.
The usePrevious hook helps track past state or props easily.