useRenderTrack Hook
Introduction
The useRenderTrack
hook is a custom React hook that allows you to track the number of times a component is rendered.
Play
Usage
- Import the
useRenderTrack
hook into your component:
import { useRenderTrack } from "@cannonui/reacthooks";
- Initialize the hook in your component:
import { useState, StrictMode } from "react";
import { useRenderTrack } from "@cannonui/reacthooks";
const TestUserRenderTrack = () => {
const [value, setValue] = useState(0);
const renderTrack = useRenderTrack();
const handleIncrement = () => {
setValue((value) => value + 1);
};
return (
<StrictMode>
<button onClick={handleIncrement}>increment</button>
<div>increment times: {value}</div>
<div>actually rendered times: {renderTrack} times</div>
</StrictMode>
);
};
export default TestUserRenderTrack;
How it Works
The useRenderTrack
hook utilizes the useRef
hook from React to keep track of the number of times the component is rendered. It creates a ref named renderTrack
and increments its value every time the component renders.
Example
In the example above, we have created a simple component TestUserRenderTrack
that uses the useRenderTrack
hook to track the number of times it’s rendered. The component also provides a button that increments a counter (value
) when clicked.
The hook ensures that the rendering count (renderTrack
) is accurately tracked, even if the component’s state changes due to user interactions or other updates.
This custom hook is helpful when you need to monitor the frequency of component renders for performance optimization or debugging purposes.
Please note that the hook only tracks the number of renders on the client-side and may not be accurate during server-side rendering or when running on the server.