Blog>
Snippets

Persisting Values Across Renders without Re-rendering

Provide an example where useRef is used to keep track of values between component renders without triggering a re-render, like storing the previous props or state value.
import React, { useRef, useEffect } from 'react';

function MyComponent(props) {
  // Create a ref to store the previous props value
  const previousProps = useRef(props);
  
  useEffect(() => {
    // After every render, update the current props to the ref
    previousProps.current = props;
  });

  // Now previousProps.current will hold the props value from last render
  
  // Rest of your component logic...
  
  // Example logic to check if the previous prop is different from current
  if (previousProps.current.someValue !== props.someValue) {
    // Do something if prop has changed
    console.log('Prop has changed');
  }

  return (
    <div>
      {/* Component render output */}
    </div>
  );
}
This example shows how to use useRef to persist the value of props across renders without causing additional re-renders. The value of the previous props is stored in a ref and updated after each render via useEffect, enabling the comparison of current props with those of the previous render.