Use this magical Babel plugin and get a performance boost for your React components

Eytan Manor
Jan 21 · 2 min read

With the introduction of React hooks (in React 16.8-alpha) arose an issue — calculations are being unnecessarily re-evaluated due to declarations being done within the rendering phase.

To put things simple, if now we’re using class components, and we store calculation results on the class instance to save ourselves some precious processing power:

In the near future, we will have no choice but to do everything within the rendering method itself, dictated by hooks:

To solve this problem, the React team invented a couple of methods: useCallback() and useMemo(). Each of them is used for different reasons but they’re quiet similar, and essentially they’re used as guard functions that will re-activate themselves only if certain parameters were changed. I recommend you to go through the official React docs to get a better perspective on these. If we were to implement it in the example above, it should look like so:

Wait a minute… So does it mean that I have to wrap all my declarations in these hooks just to get performance which is on a par with class components?!

That’s right Vladimir. Even the React team suggested that, and I quote from their docs:

“In the future, a sufficiently advanced compiler could create this array automatically” — React

It’s a good thing I love React and I think of the future. That’s why I invented this Babel plug-in called babel-plugin-react-persist, and it addresses exactly that issue! All you have to do is edit your .babelrc file and the code will be automatically transformed! Not only that, the plug-in also takes care of optimizing inline anonymous functions in JSX attributes. This way each rendering phase will have a similar instance of the intended callback. So given the following code:

The plug-in will generate:

So what are you waiting for? Go visit the official GitHub repo and get yourself a copy of the plug-in! Have any suggestions or feature request? Feel free to open a ticket in the repo’s issues page or comment below!

The Guild

The Guild

Eytan Manor

Written by

Eytan is a JavaScript artist who comes from the land of the Promise(). His hobbies are eating, sleeping; and open-source… He loves open-source.

The Guild

The Guild

The Guild

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade