Optimizing function component rendering

Our Confirm component is actually being rendered more than it needs to be. In this section, we are going to optimize this so that it only renders when its props change:

  1. First, let's add a line at the top of our function component, so that we can see when it renders:
console.log("Confirm rendering");

If we look at the running app and the console, we'll see that a render occurs every time the App component counts down. The countdown is in the App component state, and a change to state means the component will be rendered again, along with any child components. This is why, without any optimization, our Confirm component renders on each countdown.

  1. On to the optimization then. It's actually really simple:
const ConfirmMemo = React.memo(Confirm);
export default ConfirmMemo;

So, we wrap our component with a function called memo from React. We then export this wrapper function. The memo function then only renders the component if its props change.

If we look at the running app and the console, we'll see that our component no longer renders on each countdown.

So, given how simple this is, shouldn't we just wrap all our function components with memo? No! There is a performance cost when memo determines whether a component has changed. If the component doesn't actually do any unnecessary rendering, using memo would result in the component being slower. 

memo should be used with care, and only on components that are being rendered more than they need to be.

Given that the features of class components and function components are similar, which type should we be using? There is no straightforward answer, really. If our team is used to object-oriented code, perhaps class-based components will be easier to learn. If our team is used to more functional programming techniques, then function-based components may enable them to be more productive.

Both approaches are great ways to create React components—it's down to you to choose!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.206