DEV Community

Discussion on: Hacking React Hooks: Shared Global State

Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

The short answer is "no" - sorta. One thing I'm still learning about - years after I originally started doing React - is that "re-render" does not always equal "bad". And just because the render cycle is invoked, doesn't necessarily mean that anything was changed, that the component was rebuilt, or that the operation was expensive.

If you have 10 layers in a hierarchy of functional components, and you make a change to the top layer at Level 1, it is true that all of the downstream components in levels 2-10 will be called again. This does not mean that all of the downstream components in levels 2-10 will be updated/rebuilt in any way.

This is from the React docs regarding the reconciliation process:

It is important to remember that the reconciliation algorithm is an implementation detail. React could rerender the whole app on every action; the end result would be the same. Just to be clear, rerender in this context means calling render for all components, it doesn’t mean React will unmount and remount them. It will only apply the differences following the rules stated in the previous sections.

I think part of the confusion comes from React's core nomenclature. We often talk about rendering and the rendering cycle. And of course, in class components, there is even a render() function. But I think this causes some confusion (I know it does for me). Because, in React, render() doesn't mean "reconstruct the display of this component every time this function is called." Instead, it means, "If this function has never before been called, then construct the display of this component. If this function is being called after the initial construction, then invoke the diffing algorithm to see if we need to reconstruct the display in any way. If we don't need to reconstruct the display, then do nothing."

From everything I've read on the subject, it seems that invoking the diffing algorithm is cheap. The expensive part happens when the diffing algorithm indicates that we need to reconstruct some portion of the display. I've even noticed this anecdotally, although I don't have any empirical performance tests to share that back up my observations.