Join the discussion
Comments
Loading comments...
Cookie preferences
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Join the discussion
Loading comments...
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
React.memo shallow comparison se unchanged child components ka rendering kaise skip karta hai.
Default roop se, React ek component re-render karta hai jab bhi uska parent re-render karta hai â chahe component ke apne props change hue hon ya nahi. React.memo ek higher-order component hai jo ek functional component wrap karta hai aur uske render output ko memoize karta hai. Yeh previous aur naye props ka shallow comparison karta hai, aur agar woh equal hain toh re-rendering skip karta hai.
Jab parent component ki state change hoti hai, React parent ka function call karta hai. Phir woh return kiye gaye saare JSX children process karta hai â unke functions bhi call karta hai, chahe unke props identical hon. Yeh tree ke neeche cascade hota hai.
React.memo(Component) ek naya component return karta hai. Component ka function call karne se pehle, React check karta hai ki naye props shallowly equal hain previous props ke. Agar haan, React previous render output reuse karta hai â function call poori tarah skip karta hai.
Har prop key ke liye, React oldProp === newProp compare karta hai. Primitives (string, number, boolean) value se compare hote hain. Objects aur functions reference se compare hote hain â props mein ek naya object literal '{''}' hamesha equality check fail karta hai.
React.memo(Component, arePropsEqual) ek doosra argument accept karta hai â ek custom comparison function. Re-render skip karne ke liye true return karein (props equal hain), allow karne ke liye false. Deep equality checks ya specific props ignore karne ke liye useful.
React.memo sirf prop changes ki wajah se hone wale re-renders skip karta hai. Agar component useContext() call karta hai, toh woh phir bhi re-render karega jab context value change hogi â React.memo se regardless.
HOC jo component ke render output ko memoize karta hai. Re-render skip karta hai jab props previous render ke shallowly equal hon.
Har prop ko Object.is() se compare karta hai. Primitives ke liye effective. Objects aur functions renders ke across same reference maintain karni chahiye.
Jab React.memo determine karta hai ki props equal hain, woh previous render output return karta hai aur component function call skip karta hai.
Renders ke across same object/function reference rakhna. React.memo ko non-primitive props ke saath correctly kaam karne ke liye required.
Ek re-render jahan output previous render se identical hai. React.memo yeh rokta hai jab props logically nahi bade hain.
1// Without memo â re-renders every time parent renders2function ExpensiveList({ items }) {3 return items.map(item => <Item key={item.id} {...item} />);4}56// With memo â skips re-render if items reference is stable7const ExpensiveList = React.memo(function ExpensiveList({ items }) {8 return items.map(item => <Item key={item.id} {...item} />);9});1011function Parent() {12 const [count, setCount] = useState(0);1314 // â New array every render â memo never helps15 const items = [{ id: 1, name: 'Apple' }];1617 // â Stable reference â memo works as expected18 const items = useMemo(() => [{ id: 1, name: 'Apple' }], []);1920 return (21 <>22 <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>23 <ExpensiveList items={items} /> {/* skips re-render when only count changes */}24 </>25 );26}
Complex components wale large React trees mein, unnecessary re-renders real performance problems mein accumulate ho jaate hain â slow interactions, dropped frames, laggy animations. React.memo aapko surgically specific components ko re-render karne se rokne deta hai, expensive subtrees stable rakhta hai jabki app ka baaki hissa freely update hota hai.
A Slack-like app renders a message list. When a user types in the input box, the entire list of 1000+ message components re-renders because the parent (ChatRoom) updates on every keystroke.
Each keystroke updates the parent's `inputValue` state, triggering a re-render. Without React.memo, all 1000 Message components re-render even though none of their props changed. Each Message component does string formatting and date calculations â the combined cost creates visible lag.
Wrap Message in React.memo: `const Message = React.memo(({ text, author, timestamp }) => { ... })`. Since the message props are primitive values (strings, numbers), React.memo's shallow comparison correctly identifies that nothing changed. The 1000 messages are skipped entirely â only the input re-renders.
Takeaway: React.memo shines when a parent re-renders frequently but a child's props rarely change. The ideal candidates are list items, complex charts, and any component with expensive rendering where the parent updates for unrelated reasons.
A MapWidget receives a `coordinates` object `{ lat: 40.7, lng: -74.0 }`. Despite wrapping in React.memo, it still re-renders because the parent creates a new coordinates object each render.
React.memo uses shallow comparison by default: `oldCoords !== newCoords` is always true because each render creates a new object, even if lat/lng values are identical. Shallow comparison checks reference equality, not value equality.
Provide a custom comparison: `React.memo(MapWidget, (prev, next) => prev.coordinates.lat === next.coordinates.lat && prev.coordinates.lng === next.coordinates.lng)`. Now React.memo compares the actual values instead of the object reference. Alternatively, flatten the props: `<MapWidget lat={40.7} lng={-74.0} />` â primitives compare by value automatically.
Takeaway: Use custom areEqual functions for components that receive objects or arrays as props and can't be easily memoized upstream. But first, consider if you can flatten the props to primitives or memoize the object with useMemo in the parent â these are simpler and more maintainable.