Preventing unnecessary re-rendering with React.memo

With class components we had shouldComponentUpdate, which would prevent components from re-rendering if the props did not change.

With function components, we can do the same using React.memo, which is a higher-order component. React.memo memoizes the result, which means that it will remember the last rendered result, and, in cases where the props did not change, it will skip re-rendering the component:

const SomeComponent = () => ...

export default React.memo(SomeComponent)

By default, React.memo will act like the default definition of shouldComponentUpdate, and it will only shallowly compare the props object. If we want to do a special comparison, we can pass a function as a second argument to React.memo:

export default React.memo(SomeComponent, (prevProps, nextProps) => {
// compare props and return true if the props are equal and we should not update
})

Unlike shouldComponentUpdate, the function that is passed to React.memo returns true when the props are equal, and thus it should not update, which is the opposite of how shouldComponentUpdate works! After learning about React.memo, let's try it out in practice by implementing React.memo for the Post component.

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

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