14. React.memo || React.PureComponent , useCallBack(), useMemo() - florypaul/ReactJS GitHub Wiki

https://medium.com/geekculture/great-confusion-about-react-memoization-methods-react-memo-usememo-usecallback-a10ebdd3a316 https://kentcdodds.com/blog/usememo-and-usecallback

https://reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html

Memoizing

Memoizing - is a computing term -> caching results (remember) -

  • React.memo is used to wrap React Function components to prevent re-renderings. Check prop change
  • The useCallback is used to memoize functions add-to-cart function example
  • The useMemo is used to memoize values mostexpensive item price display example

User Profiler - devTools plugin to check the performance of each components and decide what to memoize accordingly.

React.memo()

React.memo() looks for change in the props and re-renders only if the prop value has changed It is a performance optimization tool, for function components instead of classes. If our function component renders the same result given the same props, React will memoize, skip rendering the component, and reuse the last rendered result. React.memo only checks for prop changes. If a function component wrapped in React.memo has a useState, useReducer or useContext Hook in its implementation, it will still re-render when state or context change.

Every time prop or state changes, say click of a button in main then the components re-render.

const MyComponent = React.memo(function MyComponent(props) { /* render using props */ });

When to use React.memo:

We can use React.memo if React component:

1-Will always render the same thing given the same props (i.e, if we have to make a network call to fetch some data and there’s a chance the data might not be the same, do not use it).

2- Renders expensively (i.e, it takes at least 100ms to render).

3- Renders often.

If our component does not meet the above requirements, then we might not need to memoize it as using React.memo, in some cases, make performance worse as it’s more code for the client to parse.

React.PureComponent

We can do the same with **class-based components **like functional components wrap the function component with React.memo(), but here we will extend the PureComponent in the class component.

React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

If our React component’s render() function renders the same result given the same props and state, we can use React.PureComponent for a performance boost in some cases.

class PercentageStat extends React.PureComponent {

render() { const { label, score = 0, total = Math.max(1, score) } = this.props;

`return (`
  `<div>`
    `<h6>{ label }</h6>`
    `<span>{ Math.round(score / total * 100) }%</span>`
  `</div>`
`)`

}

}

export default PercentageStat;

useCallback():

React’s useCallback Hook can be used to optimize the rendering behavior of our React function components. useCallback() - memoizes a function It will check if the value for a function has changed, if it has changed the the function is re-executed, else it will not execute.

Example of an "Add to cart" button on Product display page, but the function is in the js const [cart,setCount] = useState(0);

`const addToCart = useCallback(() => { setCart(cart+1) },[cart]) //also add the dependency array with cart state, to check if cart state is updated then call the function.

useCallback use case

we are writing a function getProducts() to fetch data and we are calling that function in useEffect() But we are getting an error in console - "React Hook useEffect has a missing dependency : "getProducts" error"

we can pass getProduct in the dependency array, but it will lead to an infinite loop, as it will keep re-rendering Solution is to, pass getProduct in the dependency array and use useCallback hook on the getProducts function to re-render only if there is a change.

useMemo():

useMemo() deals with a value, where it remembers the value and re-renders only if there was a change in the value useMemo() is a built-in React hook that accepts 2 arguments — a function that computes a result and the dependencies array.

example - say we are displaying list of products and we want to calculate the most expensive item cost/value. We write a function and call that function. Notice the function keeps calling on click of any other button on the page, even if the data is the same, meaning the same product as expensive is displaying.

in useMemo we pass a function which returns a value , and a dependency array

function calculateMostExpensiveItemCost(data){ return price }

const mostExpensive = useMemo(calculateMostExpensiveItemCost(product), [product])

<h1>{mostExpensive}</h1>

⚠️ **GitHub.com Fallback** ⚠️