ReactMedium
Why is a component re-rendering?
To find out why a component re-renders, enable "Record why each component rendered" in the React DevTools Profiler and inspect the reason: its state or a hook changed, its props changed (and which ones), its parent rendered, or a context it reads changed. Then fix the cause, usually unstable props, state held too high, or a broad context.
The possible reasons
- Its own state changed (
useState,useReducer, external store viauseSyncExternalStore). - The parent rendered: by default every child re-renders, even with identical props.
- Props changed: often only by reference (new object, array or function each render).
- Context changed: any consumer re-renders when the provider value changes; a new object value each provider render causes this every time.
- Development effects: Strict Mode double rendering, Fast Refresh.
How to investigate
- React DevTools Profiler with "why" recording; it names changed props and hook indexes.
- "Highlight updates when components render" for a live view.
- Temporary logging:
useEffect(() => console.log("rendered")), or a customuseWhyDidYouUpdatehook comparing previous and current props. - The
why-did-you-renderlibrary for detailed reports in development. - React Compiler badges ("Memo ✨") show which components are already auto-memoized.
Typical fixes
- Unstable props: memoize them or move them out of render (or enable the React Compiler).
- Parent re-renders: move state down, pass static parts as
children, or wrap the child inmemo. - Context: split it, memoize the value, or use a store with selectors.
- Remember that a re-render is not necessarily slow; fix it only if it costs time.
Code example
tsx
1import { useEffect, useRef } from "react";23// Development helper: logs which props changed between renders4export function useWhyDidYouUpdate(name: string, props: Record<string, unknown>) {5 const previous = useRef<Record<string, unknown> | null>(null);67 useEffect(() => {8 if (previous.current) {9 const changes: Record<string, { from: unknown; to: unknown }> = {};10 for (const key of new Set([...Object.keys(previous.current), ...Object.keys(props)])) {11 if (!Object.is(previous.current[key], props[key])) {12 changes[key] = { from: previous.current[key], to: props[key] };13 }14 }15 if (Object.keys(changes).length) console.log(`[why-did-you-update] ${name}`, changes);16 else console.log(`[why-did-you-update] ${name}: no prop changed (parent or state/context render)`);17 }18 previous.current = props;19 });20}2122export function UserCard(props: { user: { name: string }; onSelect: () => void }) {23 useWhyDidYouUpdate("UserCard", props); // e.g. logs "onSelect" changed every render -> unstable callback24 return <button onClick={props.onSelect}>{props.user.name}</button>;25}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.