Hacker News new | ask | show | jobs
by miracle2k 2240 days ago
If I understand you correctly, you have it backwards.

If a component renders in React, that is, the render function is called, then ALL children's render() function are also called, unless you do specific optimizations such as React.memo.

So the whole tree is rerendered.

When it comes time to apply those changes to the DOM, that is, generating HTML on the page, wherever your render() functions returned the same result as before, the DOM is not touched.

3 comments

> So the whole tree is rerendered.

As you said yourself, only children components will be re-rendered. This is relative to the component that had it's state changed (using setState or the useState hook). So not the whole tree rerenders, only the affected component and it's children. And again, when we speak as "re-render", the render() functions of the components are called and then the VDOM diffing happens. That is, even if child components got -rerendered (in react terms), there might not be a DOM update at all (which is the slow, costly operation).

> That is, even if child components got -rerendered (in react terms), there might not be a DOM update at all (which is the slow, costly operation).

Crawling a large React tree's render stack is also a costly operation. Not as much as DOM manipulation but it is still costly, and React is created in such a way that it requires you to include everything in that stack, even if it never changes. Which is one reason we have Portals.

As the component tree grows in size, even the render call and diffing become a wasteful, costly operation.
(i hope i'm not spreading misinfo, i'm not super experienced with React)

it may be that way with regular Components, but afaik Pure components are smarter - the idea of Pure components is that react only rerenders the components when the props change. (or something in a hook, if you're using those). though i guess a Pure component is basically equivalent to what you'd get with memo?

Yes, PureComponent, React.memo and shouldComponentUpdate are all the same mechanism.
Yes, of course, I realized how the html re-render part works just now reading your reply, which I had known before but forgotten. sort of embarrassing.