DEV Community

Garrick Crouch
Garrick Crouch

Posted on

Optimize Renders in React.js Function Components

You may come across issues in react where transitions and animations fire more than you'd like and in some cases it may be hard to control those renders, especially when dealing with libraries. In my case I had chart animations that would fire when the component was rendered and there wasn't any easy way to throttle that or prevent the duplicate transitions.

The docs point out that

This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.

Speaking of https://reactjs.org/docs/react-api.html#reactmemo.

This is a memoization technique not afforded by component should update since we're not using class components. To the react docs point it can be buggy, but in my case it works wonders and prevents rampant animations.

import * as React from 'react';

export default React.memo(function MyComponent({
  data,
  options
}) {

  const [chartData, setChartData] = React.useState(() => {
    // some advanced filtering for the chart
    return (data || []).filter(item => item !== item + 1);
  });

  return (
    <Chart {...options} {...chartData} />
  );
});
Enter fullscreen mode Exit fullscreen mode

In this hypothetical chart component, if the parent would render, well the myComponent would rerender, which normally isn't an issue, but in our case the chart has transitions on it that trigger on every render and we cannot modify that API because it's a 3rd party. This will provide and easy way for us to still use hooks and only have the myComponent to render once, which will run our filter logic on the data and allow a performance optimization as well possibly.

Important note: hooks still work as you'd expect in a memoized component so you can use them and get renders on state change.

I think the majority use case is the intended of the react team which is performance for unnecessary renders, but this works perfectly for throttling renders in the case of UI side effects.

Top comments (0)