最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How I can count how many times my component rendered in a react component - Stack Overflow

programmeradmin1浏览0评论

I have the following React ponent,

import React, {useState} from "react"

export default function App(){
  const [state, setState] = useState(0);
  return <>
    <button onClick={() => setState(state + 3)}>Click to increment</button>
    {state}
  </>
}

I have the following React ponent,

import React, {useState} from "react"

export default function App(){
  const [state, setState] = useState(0);
  return <>
    <button onClick={() => setState(state + 3)}>Click to increment</button>
    {state}
  </>
}

How will be able to display the number of times my ponent has rendered! Thanks!

Share asked Jun 27, 2022 at 13:45 user19427099user19427099 1
  • use useRef hook – DanteDX Commented Jun 27, 2022 at 13:46
Add a ment  | 

4 Answers 4

Reset to default 7

renderCount.current represents the render count for your ponent. You can use the following code, but for react 18, the first time renderCount.current will be equal to 2, and then will increment by one. If you want the first time renderCound.current to be 1, use react 17 Thanks!

import React, { useState, useRef, useEffect } from "react";

export default function App() {
  const [state, setState] = useState(0);
  const renderCount = useRef(0);
  useEffect(() => {
    renderCount.current = renderCount.current + 1;
  });

  return (
    <>
      <button onClick={() => setState(state + 3)}>Click to increment</button>
      {state}
      {renderCount.current}
    </>
  );
}

Store a counter outside the ponent. Increment it each time the ponent renders.

let renderCount = 0;

export default function App(){
  const [state, setState] = useState(0);
  renderCount++;
  return <>
    <button onClick={() => setState(state + 3)}>Click to increment</button>
    {state}
    <p>This ponent has rendered {renderCount} times.</p>
  </>
}

Note that sometimes a ponent might be rendered extra times (e.g. for Strict Mode tests).

i saw in other post and option to just add

console.count('counter')

with in your code and then each time the ponent renders it will update the counter

If you are working on a big project, create a custom hook. In this way, u can tackle unnecessary renders.

Creating Custom Hook for renderCount.

import { useRef, useEffect } from "react";

export default () => {
  const renderCount = useRef(0);
  useEffect(() => {
    renderCount.current++;
  });
  return renderCount.current;
};

then access it from any ponent. let's check the example below.

function Counter() {
  const renderCount = useRenderCount();
  const [counter, setCounter] = useState(0);
  return (
    <div>
      <button onClick={() => setCounter(counter + 1)}>
        Counter value: {counter} | Render Count: {renderCount}
      </button>
    </div>
  );
}
发布评论

评论列表(0)

  1. 暂无评论