दुवैले कुनै कुरा render भरि cache गर्छन् जसले गर्दा यो हरेक पल recompute/recreate हुँदैन:
- ले लाई cache गर्छ।
दुवैले कुनै कुरा render भरि cache गर्छन् जसले गर्दा यो हरेक पल recompute/recreate हुँदैन:
useMemouseCallback ले function को identity लाई cache गर्छ (यो useMemo(() => fn, deps) हो)।तिनीहरु (a) महँगो काम दोहोर्याउनबाट र (b) memoized children हरुले भर पर गरेको referential equality तोड्नबाट बच्नका लागि अस्तित्वमा छन्।
function Table({ rows, onSelect }) {
// (a) expensive computation — recompute only when `rows` changes
const sorted = useMemo(() => rows.slice().sort(byName), [rows]);
// (b) stable function identity — so a React.memo child doesn't re-render,
// and effects depending on it don't re-fire
const handleSelect = useCallback(id => onSelect(id), [onSelect]);
return <Grid rows={sorted} onSelect={handleSelect} />;
}
useCallback बिना, handleSelect हरेक render मा बिल्कुल नयाँ function हो। एक React.memo(Grid) ले "नयाँ" prop देख्नेछ र जहिले पनि re-render हुनेछ, memoization लाई हराउदै। यही कुरा memoized child लाई पारिएको object वा useEffect dependency array मा प्रयोग गरिएको object को लागि पनि हो।
const x = useMemo(() => a + b, [a, b]); // ❌ pointless — adding is cheaper than memoizing
useMemo/useCallback ले शोर थप्छ र गति पनि ढिलो हुन सक्छ। (React 19 को compiler auto-memoize गर्न सक्छ, आवश्यकता घटाउँदै।)