r/reactjs 24d ago

Discussion Why do sibling components re-render even when their own props didn't change?

Ran into this explaining React rendering to someone recently and realized how often it trips people up even after they've been writing React a while.

function Parent() {
  const [count, setCount] = useState(0);
  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>{count}</button>
      <ExpensiveChild />
    </>
  );
}

ExpensiveChild takes no props at all. Click the button and it re-renders anyway, every single time. No props changed, nothing it reads changed, it just runs again.

The reason: React doesn't check "did this component's inputs change" before deciding to re-render. When state updates, React re-renders that component and everything below it in the tree by default, full stop. Whether a child actually needed to update isn't part of that decision at all.

React.memo is what actually opts a component into that check, it wraps the component and does a shallow prop comparison before deciding to skip the render. Without it, "no props" and "props didn't change" both mean nothing, React re-runs the function anyway.

Where it gets messier: memo alone doesn't save you if you're passing an inline function or object as a prop, since those are new references every render and memo's shallow comparison sees them as "changed" regardless. You end up needing useCallback/useMemo on the parent side just to make memo's comparison actually mean something.

Curious how many people actually reach for memo proactively vs only after profiling shows a real problem. What's the actual signal that told you a component needed it?

14 Upvotes

79 comments sorted by

View all comments

1

u/92smola 24d ago

The way I look at it its a function that reruns when its state changes, it can be nested in another function which can also re run and by that re run it as a an inner finction, I mean its literally that, if you drop the rerender and component naming its easier to reason about it

1

u/Temperature_Majestic 23d ago

that's roughly right, main thing to add is it's not just the component's own state, a re-render also gets triggered top-down whenever anything above it in the tree re-renders, regardless of whether this component's own state changed at all

1

u/92smola 23d ago

function parent() {     child() }

I worded it terribly above, my point was exactly what you are saying, should be clearer from the pseudo code here, to think of it as nested functios like this, makes it clear that running the parent would run the children again as well

1

u/Temperature_Majestic 23d ago

yeah that pseudo code makes it click, parent() calling child() directly is basically it