import React, { useEffect, useRef, useState, memo } from 'react';
const ExpensiveComponent = memo(({ onRender }) => {
useEffect(() => {
onRender();
}, [onRender]);
return <div>Expensive component</div>;
});
export default function App() {
const renderCountRef = useRef(0);
const [count, setCount] = useState(0);
const handleRender = () => {
renderCountRef.current += 1;
console.log('Component render count:', renderCountRef.current);
};
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 2000);
return () => clearInterval(id);
}, []);
return (
<div>
<h1>Count: {count}</h1>
<ExpensiveComponent onRender={handleRender} />
</div>
);
}
This is coming automatically multiple times?
Component render count: 1
Component render count: 2
Component render count: 3
Component render count: 4
Component render count: 5
I have a dashboard with many components, and i try to pass functions as props to deeply nested children. Every time a parent re-renders, these functions are get re-created, causing memoized children to re-render unnecessarily.