Blog>
Snippets

Preventing Unnecessary Renders with useRef

Show the use of useRef to store current state without causing re-renders and compare it to useState to highlight how useRef can prevent unnecessary component updates.
import React, { useState, useRef } from 'react';

function App() {
  // Using useState, changes cause re-renders
  const [count, setCount] = useState(0);

  // Using useRef, changes do not cause re-renders
  const countRef = useRef(0);

  const incrementCount = () => {
    setCount(count + 1); // This will re-render the component
  };

  const incrementCountRef = () => {
    countRef.current += 1; // This will not re-render the component
  };

  return (
    <div>
      <p>Count: {count}</p>
      <p>CountRef: {countRef.current}</p>
      <button onClick={incrementCount}>Increment Count</button>
      <button onClick={incrementCountRef}>Increment CountRef</button>
    </div>
  );
}

export default App;
In this example, we have a React component called App with two counters. One uses useState and the other uses useRef to store the current count. The `incrementCount` function updates the state using `setCount`, which triggers a re-render of the component to reflect the new value. In contrast, `incrementCountRef` function increases the value of `countRef.current` without re-rendering because changes to `ref.current` do not notify React of the change.