skip to Main Content

Given this simple example:


import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  console.log("Component rerendered");

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

export default Counter;`

I want this component to re-render when Count equals X number.

The problem at hand is a component that has hundreds of re-renders due to necessary state updates. I wish to have a better control of these re-renders due to performance issues.

2

Answers


  1. One possible solution might be to track the count with a ref from useRef.

    function Counter() {
      const [count, setCount] = React.useState(0);
      const countRef = React.useRef(0);
    
      const handleClick = () => {
        countRef.current += 1;
        
        if(countRef.current % 10 === 0) {
          setCount(countRef.current);
        }
      };
    
      console.log("Component rerendered");
    
      return (
        <div>
          <h1>{count}</h1>
          <button onClick={handleClick}>Increment</button>
        </div>
      );
    }
    
    const root = ReactDOM.createRoot(document.getElementById('app'));
    root.render(<Counter />);
    <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    
    <div id="app"></div>
    Login or Signup to reply.
  2. Try this:

    import React, { useState} from 'react';
    
    function Counter() {
      let temp = 0;
      const [count, setCount] = useState(temp);
      let X = 5;
      const handleClick = () => {
        temp++;
        if (temp == X) {
          setCount(temp);
        }
      };
    
      console.log('Component rerendered');
      return (
        <div>
          <h1>{count}</h1>
          <button onClick={handleClick}>Increment</button>
        </div>
      );
    }
    
    export default Counter;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search