I have the following React component,
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 component has rendered! Thanks!
Store a counter outside the component. Increment it each time the component 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 component has rendered {renderCount} times.</p>
</>
}
Note that sometimes a component might be rendered extra times (e.g. for Strict Mode tests).
renderCount.current represents the render count for your component. 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}
</>
);
}