?? React.Memo (Bonus)

?? React.Memo (Bonus)

Mastering React Hooks: A Beginner's Guide to useMemo [cont.]

What is React.memo?

React.memo is a higher-order component (HOC) that optimizes functional components by memoizing them. It prevents unnecessary re-renders by "remembering" the component's last-rendered output. If a component's props don’t change between renders, React.memo will skip re-rendering that component, saving processing time and enhancing performance.

How Does React.memo Work?

React.memo wraps a functional component and compares the previous props with the new ones. If they’re the same, React skips rendering that component. This is especially useful for components that receive complex or nested props, as they can trigger re-renders even when the props haven’t changed.

Here’s a simple usage example of React.memo:

import React from 'react';

// Memoized component to prevent re-render if props haven't changed
const MyComponent = React.memo(({ value }) => {
  console.log('Rendering MyComponent');
  return <div>{value}</div>;
});

function Parent() {
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <MyComponent value="Static Prop" />
      <button onClick={() => setCount(count + 1)}>Increase Count</button>
    </div>
  );
}        

Explanation:

In this example:

  • MyComponent is wrapped with React.memo, so it will only re-render if the value prop changes.
  • Since value remains the same, clicking the button only triggers a re-render of the Parent component, and MyComponent remains unaffected.

Right & Wrong Approaches

Using React.memo with props that don’t frequently change:

  • ? Correct: Wrapping components with expensive or frequent re-renders, or those receiving complex props that don't change often.

Using React.memo with frequently changing props:

  • ? Incorrect: Overusing it for all components, especially with dynamic data props, as it adds overhead.

When Should You Use React.memo?

  • For pure components that rely only on props and don’t need to re-render when parent components update.
  • For components with complex props (like large arrays or objects) that rarely change, to reduce re-render frequency.

Overuse can add complexity without significant performance benefit, so reserve React.memo for components where re-rendering has a noticeable impact.

?? Difference Between React.memo and useMemo

Purpose

  • React.memo: A Higher-Order Component (HOC) used to prevent a component from re-rendering if its props haven’t changed. It’s particularly helpful for functional components that don’t need to update on every parent render.
  • useMemo: A React hook used to memoize the result of an expensive function, recalculating it only when dependencies change. It’s primarily for caching values within a component to avoid recalculating them on each render.

Usage

React.memo is applied to entire functional components to prevent re-renders:

const MyComponent = React.memo((props) => {
  // Component logic here
});        

useMemo is used to memoize values or results inside a component:

const memoizedValue = useMemo(() => expensiveFunction(data), [data]);        

Use Case

  • React.memo optimizes the re-rendering of components, especially useful when passing complex or frequently changing props to child components.
  • useMemo optimizes costly computations or calculations within a component, recalculating only when dependencies change.

Limitations

  • React.memo: The component will still re-render if the parent re-renders, even if the props are identical. React.memo only works at the component level, not for individual values or functions.
  • useMemo: Should be reserved for computationally heavy functions since it has some memory overhead; overusing it can lead to cluttered code without significant performance gains.

Example Comparison

Consider a parent component rendering a ChildComponent that has complex props and heavy calculations:

// Using React.memo to prevent unnecessary re-renders of ChildComponent
const ChildComponent = React.memo(({ data }) => {
  // Without React.memo, this would re-render on every parent render, even if props are the same
  return <div>{data}</div>;
});

function ParentComponent() {
  const data = { name: 'React' };

  // Using useMemo to memoize a complex calculation
  const memoizedCalculation = useMemo(() => heavyCalculation(data), [data]);

  return <ChildComponent data={memoizedCalculation} />;
}        

?? Summary

  • Use React.memo for components to avoid unnecessary re-renders when props don’t change.
  • Use useMemo within components to cache expensive calculations based on dependency changes.

Together, these tools complement each other to optimize React app performance effectively.

?? Tip:

Use React.Memo to memoize Pure Components or Components with complex props to prevent a component from re-rendering if its props haven’t changed. Happy coding!



Sridhar Raj P

?? On a mission to teach 1 million students | Developer & Mentor | 5,500+ Students ??| JavaScript | React JS | Redux | Python | Java | Springboot | MySQL | Self-Learner | Problem Solver

1 个月

Thanks for sharing! ????

SRINIVAS K

Software Engineer specializing in React, TypeScript, JavaScript and Next.js | Building Scalable Web Applications with a Focus on Performance

2 个月

checkout the new article to cache the functions in your React app using useCallback: --> https://www.dhirubhai.net/posts/srinivasthedeveloper_reactjs-reacthooks-usecallback-activity-7260640753297547264-gByi

回复

要查看或添加评论,请登录

SRINIVAS K的更多文章

社区洞察

其他会员也浏览了