Sobes.tech
Middle

Why does a re-render occur when calling handleClick with setCount, and how to avoid re-rendering while preserving the variable?

sobes.tech AI

Answer from AI

When calling setCount, the state is updated, which causes the React component to re-render in order to display the new value.

To store a variable without causing a re-render, you can use useRef. The value in useRef can be changed without triggering a component update.

Example:

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

function Counter() {
  const [count, setCount] = useState(0);
  const countRef = useRef(0); // variable that does not trigger re-render

  const handleClick = () => {
    setCount(count + 1); // updates state and causes re-render
    countRef.current += 1; // changes value without re-render
  };

  return (
    <div>
      <p>Count (state): {count}</p>
      <p>Count (ref): {countRef.current}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

Thus, useRef allows storing a mutable value between renders without causing re-renders.