This is a very simplified explanation, but as you can see, it's actually already quite complicated. So anyone who used those hooks in real life knows how hard it is to trace those changing references and how quickly our beautiful apps turn into an incomprehensible and unusable mess of useMemo and useCallbacks. So solving this situation is React Compiler's main promise.
The compiler is a tool given to us by the React team. It plugs into our build system, grabs the original component code, and then tries to convert it into code where components, the props, and dependencies of hooks are memoized by default. The end result is as if our normal React code behaves as if everything is wrapped in memoUse, memoUseCallback, which is already very cool. But it doesn't actually do this. It doesn't wrap things blindly. It's much smarter than that.
For example, something as simple as this will be transformed into this. Notice how onClick is cached at the very bottom, but the data object is not really cached. It just moved inside the if statement. However, if I reference this data inside onClick, the compiler understands this and rearranges the code to sound like this. Mechanics of all of this are absolutely fascinating. However, in this case, I'm more interested in practical applications of this engineering miracle.
So more specifically, I want to know whether our expectations from the compiler match the reality. And three main questions immediately pop into mind for almost everyone. First one is, what about the initial load performance? One of the big arguments against memoizing everything by default has always been that it can negatively affect initial load, because React needs to do much more stuff in advance where everything is memoized. Second one is, will it actually have a positive impact at all? How much of a problem re-renders really are? And the third one is, JavaScript is notorious for being fluid and ambiguous. Is the compiler smart enough to really catch absolutely everything? Is it true that we will never have to think about memorization and re-renders ever again? Before answering those questions, let's quickly check out the compiler on a few synthetic examples. Maybe, who knows, maybe it doesn't work at all.
So our first example, we have a component with a dialogue, a state for this dialogue, and a button that can open it. And a very slow component somewhere underneath. So let's say it takes five milliseconds to re-render. Normal React behavior here would be to re-render everything, including the very slow component when the state changes. And as a result, the dialogue pops up with a delay because of the slow component. If I wanted to fix it with memoization, I would have to do this. Just wrap it in the React memo. Let's get rid of it and enable the compiler for this code and see what will happen. In the dev tools, I see the magical memo appearing everywhere, the blue stuff.
Comments