idev0085 / react-boilerplate

0 stars 0 forks source link

How do you memoize a component? #77

Open idev0085 opened 3 years ago

idev0085 commented 3 years ago

.When a component is wrapped in React. memo() , React renders the component and memoizes the result. Before the next render, if the new props are the same, React reuses the memoized result skipping the next rendering

React.memo is a higher order component.

If your component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.

React.memo only checks for prop changes. If your function component wrapped in React.memo has a useState, useReducer or useContext Hook in its implementation, it will still rerender when state or context change.

By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.

This method only exists as a performance optimization.

import React from 'react';
function areEqual(prevProps, nextProps) {
    console.log("prevProps", prevProps)
    console.log("nextProps", nextProps)
}
export function Movie({ title, releaseDate }) {
    return (
        <div>
            Movie title: {title}
            Release date: {releaseDate}
        </div>
    );
}
export default React.memo(Movie, [areEqual]);