By : admin
Language: javascript
Date Published: 1 month ago
React.memo is a higher‑order component that shallowly compares props and skips re‑rendering when they haven’t changed. In medium‑sized apps, frequent re‑renders of presentational components (like buttons, cards, or tooltip widgets) can waste CPU cycles, especially when they are deep in the tree or render large lists. By wrapping such components in React.memo, you let React bail out early when the parent updates unrelated state.
Use it judiciously: memoization helps when props are primitive values or stable object references (e.g., using useCallback for handlers). Avoid memoizing components that receive frequently changing objects or arrays unless you stabilize them first, as the shallow compare will deem them different and defeat the purpose. Pair React.memo with useCallback for event handlers and useMemo for expensive derived values to keep referential equality intact. This pattern keeps UI snappy without sacrificing readability, and it’s safe to apply broadly to leaf components that are pure in nature.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | // Button.jsx – a presentational button that rarely needs to re‑render import React from "react"; const Button = React.memo(({ label, onClick, disabled = false }) => { console.log(`Rendering Button: ${label}`); // for demo; remove in prod return ( <button onClick={onClick} disabled={disabled} className="btn"> {label} </button> ); }); export default Button; // App.jsx – demonstrates usage import React, { useState, useCallback } from "react"; import Button from "./Button"; export default function App() { const [count, setCount] = useState(0); const [name, setName] = useState(""); // Stable reference thanks to useCallback const handleIncrement = useCallback(() => setCount(c => c + 1), []); return ( <div className="app"> <h1>Counter: {count}</h1> <Button label="Increment" onClick={handleIncrement} /> {/* This button receives a changing prop (name) – will re‑render on each keystroke */} <Button label={`Hello, ${name}`} onClick={() => alert(name)} /> <input value={name} onChange={e => setName(e.target.value)} placeholder="Enter name" /> </div> ); } |