import React, { FC, useCallback, useRef, useState } from "react";
const ExpensiveTree = React.memo<{ [key: string]: any }>(({ showCount }) => {
const renderCountRef = useRef(0);
renderCountRef.current += 1;
return (
Render Count: {renderCountRef.current}
);
});
const About: FC = () => {
const [count, setCount] = useState(0);
const callbackFn = useCallback(() => {
// eslint-disable-next-line no-alert
alert(`Current count is ${count}`);
}, [count]);
return (
<>
count: {count}
You can click the button to see the number of sub-component renderings
Component with useCallback function:
{/* use callback function, ExpensiveTree component will re-render on state change */}
Component with useMemoizedFn function:
{/* use memoized function, ExpensiveTree component will only render once */}
>
);
};
export default About;