Master React Rendering: When to Re‑Render and How to Skip Unnecessary Updates
This article explains how React decides when to re‑render components, why default behavior can be costly, and how developers can use state changes and the shouldComponentUpdate method to control rendering and improve performance.
Why React Re‑renders
React is famous for its performance because it uses a virtual DOM layer and updates the real DOM only when necessary, which is much faster than constantly updating the DOM directly. However, React’s intelligence stops at this point; developers must understand its expected behavior and limitations to avoid accidental performance loss.
When Does React Re‑render a Component?
React decides to re‑render a component when its state changes (including changes from props or a direct
setStatecall). By default, every state change triggers a re‑render, even if the visual output does not actually change.
Examples:
Component state changes → re‑render.
Parent component changes → re‑render.
Props change that does not affect the view → still re‑render.
In a deliberately exaggerated example, a Todo component re‑renders every second even though the
unseenvalue never changes, demonstrating the cost of unnecessary renders.
2. Using shouldComponentUpdate
The
shouldComponentUpdatemethod returns
true</strong> by default, which is why every update causes a re‑render. By overriding this method, developers can tell React when a re‑render is truly needed.</p><p>When React is about to render a component, it calls <code>shouldComponentUpdate. If the method returns
false, the render is skipped. Therefore, you need to rewrite
shouldComponentUpdateto return
trueor
falsebased on the data that actually matters for rendering.
In the Todo example, only changes to
titleor
doneshould trigger a re‑render; changes to
unseencan be ignored.
After applying the optimization,
setStatestill runs every second, but
renderis called only on the initial load or when
titleor
donechange.
Important Note
Returning
falsefrom a parent’s
shouldComponentUpdatedoes not prevent child components from re‑rendering due to their own state changes. It only stops updated props from being passed down.
Additional Content: Simple Performance Test
Writing and executing code inside
shouldComponentUpdatecan be expensive, so you should first measure how much time a normal React update cycle consumes. Use React’s performance tools to identify wasted cycles and make informed optimization decisions.
Identify which components waste the most rendering cycles and use
shouldComponentUpdateto make them smarter.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.