国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Key Points
How to render UI with React
Why do we need React memory
Memorization in React
Implement memory in class components
Implement memory in functional components
React.memo() Problems with function prop
useCallback() to avoid further rerendering
Precautions
Summary
Home Web Front-end JS Tutorial How to Implement Memoization in React to Improve Performance

How to Implement Memoization in React to Improve Performance

Feb 09, 2025 am 09:00 AM

How to Implement Memoization in React to Improve Performance

This tutorial will explain how to implement Memoization in React. Memorization improves performance by storing the results of expensive function calls and returning these cached results when needed again.

We will cover the following:

  • How to render UI with React
  • Why do you need React memory?
  • How to implement memory for functional and class components
  • Precautions about memory

This article assumes that you have a basic understanding of class components and functional components in React. If you want to review these topics, check out the official React components and props documentation.

How to Implement Memoization in React to Improve Performance

Key Points

  • Memorization in React improves performance by storing the results of expensive function calls and returning these cached results when needed again.
  • React uses virtual DOM to perform DOM updates efficiently, but for large components, the performance impact of checking virtual DOM can be very high. Memorization can help avoid unnecessary re-rendering and virtual DOM checking.
  • React.PureComponent and React.memo() can be used to implement memory in class components and functional components, respectively. These methods prevent unnecessary re-rendering if the component's props or state has not changed.
  • If a function is passed as a prop to a child component, the child component will be re-rendered even if React.memo() is used. To avoid this, you can use the useCallback() hook to prevent recreating the function every time the parent component renders.
  • Memorization should be used with caution in React applications. It works best when a component returns the same output to the same props, contains multiple UI elements (virtual DOM checks affect performance), or often provides the same props.

How to render UI with React

Before going into the detailed introduction of memory in React, let's first look at how React renders the UI using virtual DOM.

The regular DOM basically contains a set of nodes represented as a tree. Each node in the DOM is a representation of the UI element. Whenever a state change occurs in the application, the corresponding nodes of that UI element and all its child elements are updated in the DOM and then the UI is repainted to reflect the updated changes.

Using efficient tree algorithms, node updates are faster, but re-drawing is slower, and when the DOM has a large number of UI elements, it will have an impact on performance. Therefore, a virtual DOM is introduced in React.

This is a virtual representation of the real DOM. Now, whenever the state of the application changes anyway, React does not directly update the real DOM, but creates a new virtual DOM. React then compares this new virtual DOM with the previously created virtual DOM to find the differences that need to be redrawn.

Using these differences, the virtual DOM will effectively update the real DOM with changes. This improves performance because the virtual DOM does not simply update the UI elements and all its child elements, but effectively updates only the minimum necessary changes in the real DOM.

Why do we need React memory

In the previous section, we saw how React can effectively perform DOM updates using virtual DOM to improve performance. In this section, we will look at a use case that explains why memory is needed to further improve performance.

We will create a parent class with a button to increment the state variable named count. The parent component also calls the child component and passes the prop to it. We also added the console.log() statement to the render method of two classes:

//Parent.js
class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleClick = () => {
    this.setState((prevState) => {
      return { count: prevState.count + 1 };
    });
  };

  render() {
    console.log("Parent render");
    return (
      <div className="App">
        <button onClick={this.handleClick}>Increment</button>
        <h2>Count: {this.state.count}</h2>
        <Child name={"joe"} />
      </div>
    );
  }
}

export default Parent;

The full code for this example is available on CodeSandbox.

We will create a Child class that takes the prop passed by the parent component and displays it in the UI:

//Child.js
class Child extends React.Component {
  render() {
    console.log("Child render");
    return (
      <div>
        <h2>Name: {this.props.name}</h2>
      </div>
    );
  }
}

export default Child;

Whenever we click the button in the parent component, the count value changes. Since this is a state change, the render method of the parent component is called.

Props passed to subclasses remain unchanged every time the parent re-renders, so the child components should not be re-rendered. However, when we run the above code and continue incrementing the count, we get the following output:

<code>Parent render
Child render
Parent render
Child render
Parent render
Child render</code>

You can increment the count of the above example yourself in the following sandbox and view the output of the console:

[The CodeSandbox link should be embedded here, but since I can't access external websites, it cannot be provided]

From this output we can see that when the parent component re-renders, it also re-renders the child component - even if the props passed to the child component have not changed. This will cause the subcomponent's virtual DOM to perform a difference check with the previous virtual DOM. Since there is no difference in the child component - because props are the same in all re-renders - the real DOM is not updated.

We do have the performance advantage of not updating the real DOM unnecessarily, but we can see here that a new virtual DOM is created and a difference check is performed even if the child components have not actually changed. For small React components, this performance is negligible, but for large components, performance impact is great. To avoid this re-rendering and virtual DOM checking, we use memory.

Memorization in React

In the context of a React application, memorization is a technique where whenever the parent component re-renders, the child component will re-render only when props change. If props have not changed, it does not execute the render method, but returns the cached result. Since the render method is not executed, no virtual DOM and differential checks are created - thus improving performance.

Now let's see how memorization is implemented in classes and functional React components to avoid this unnecessary re-rendering.

(The following content is similar to the original text, except that the language and expression have been adjusted a little, and the image location and format are kept unchanged. I cannot provide a CodeSandbox link due to the inability to access external websites.)

Implement memory in class components

To implement memory in class components, we will use React.PureComponent. React.PureComponent implements shouldComponentUpdate(), which makes shallow comparisons between state and props and renders React components only if props or state changes.

Change the child component to the code shown below:

//Parent.js
class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleClick = () => {
    this.setState((prevState) => {
      return { count: prevState.count + 1 };
    });
  };

  render() {
    console.log("Parent render");
    return (
      <div className="App">
        <button onClick={this.handleClick}>Increment</button>
        <h2>Count: {this.state.count}</h2>
        <Child name={"joe"} />
      </div>
    );
  }
}

export default Parent;

The full code for this example is as follows: [CodeSandbox link should be embedded here]

The parent component remains unchanged. Now, when we increment count in the parent component, the output in the console is as follows:

//Child.js
class Child extends React.Component {
  render() {
    console.log("Child render");
    return (
      <div>
        <h2>Name: {this.props.name}</h2>
      </div>
    );
  }
}

export default Child;

For the first rendering, it calls the render method of the parent and child components.

In each incremental subsequent re-render, only the render function of the parent component is called. The child components will not be rerendered.

Implement memory in functional components

To implement memory in a functional React component, we will use React.memo(). React.memo() is a high-order component (HOC) that does similar work to PureComponent to avoid unnecessary re-rendering.

The following is the code for functional components:

<code>Parent render
Child render
Parent render
Child render
Parent render
Child render</code>

We also convert the parent component to a functional component as shown below:

//Child.js
class Child extends React.PureComponent { // 將React.Component更改為React.PureComponent
  render() {
    console.log("Child render");
    return (
      <div>
        <h2>Name: {this.props.name}</h2>
      </div>
    );
  }
}

export default Child;

The full code for this example can be seen in the following sandbox: [CodeSandbox link should be embedded here]

Now, when we increment count in the parent component, the console outputs the following:

<code>Parent render
Child render
Parent render
Parent render</code>

React.memo() Problems with function prop

In the example above, we see that when we use React.memo() HOC for our child components, even if the parent component is re-rendered, the child components are not re-rendered.

However, a small problem to note is that if we pass the function as a prop to the child component, the child component will be re-rendered even if we use React.memo(). Let's look at an example.

We will change the parent component as shown below. Here we add a handler function that we pass to the child component as props:

//Child.js
export function Child(props) {
  console.log("Child render");
  return (
    <div>
      <h2>Name: {props.name}</h2>
    </div>
  );
}

export default React.memo(Child); // 在此處為子組件添加HOC以進(jìn)行記憶化

The subcomponent code remains unchanged. We are not using a function passed as props in a child component:

//Parent.js
import React, { useState } from 'react';
import Child from './Child';

export default function Parent() {
  const [count, setCount] = useState(0);
  const handleClick = () => {
    setCount(count + 1);
  };
  console.log("Parent render");
  return (
    <div>
      <button onClick={handleClick}>Increment</button>
      <h2>Count: {count}</h2>
      <Child name={"joe"} />
    </div>
  );
}

Now, when we increment count in the parent component, it re-renders and re-renders the child component even if props have not changed.

So, what caused the child components to re-render? The answer is that every time the parent component re-renders, a new handler function is created and passed to the child component. Now, since the handler function is recreated every time it is rerendered, the child component will find that the handler reference has been changed when it is a shallow comparison of props and rerenders the child component.

In the next section, we will see how to resolve this issue.

useCallback() to avoid further rerendering

The main problem that causes the child component to be re-rendered is the re-creation of the program function, which changes the references passed to the child component. Therefore, we need a way to avoid this recreation. If the handler is not recreated, the reference to the handler will not change - so the child components will not be rerendered.

To avoid recreating the function every time the parent component renders, we will use a React hook called useCallback(). Hooks were introduced in React 16. To learn more about hooks, you can check out React’s official hook documentation or check out “React Hooks: How to Get Started and Build Your Own.”

useCallback()Hook accepts two parameters: callback function and dependency list.

Consider the following useCallback() Example:

//Parent.js
class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleClick = () => {
    this.setState((prevState) => {
      return { count: prevState.count + 1 };
    });
  };

  render() {
    console.log("Parent render");
    return (
      <div className="App">
        <button onClick={this.handleClick}>Increment</button>
        <h2>Count: {this.state.count}</h2>
        <Child name={"joe"} />
      </div>
    );
  }
}

export default Parent;

Here, useCallback() is added to the handleClick() function. The second parameter [x,y] can be an empty array, a dependency, or a dependency list. The handleClick() function is recreated whenever any dependencies mentioned in the second parameter change.

If the dependency mentioned in useCallback() has not changed, the memorized version of the callback function (as the first parameter) is returned. We will change our parent functional component to use the useCallback() hook for handlers passed to the child component:

(This is similar to the original text, except that the language and expression are adjusted a little, and the image position and format are kept unchanged. I cannot provide a CodeSandbox link due to the inability to access external websites.)

Precautions

Memorization is a good technique to improve React application performance by avoiding unnecessary re-rendering of components when the component's props or state has not changed. You might think of adding memorization to just all components, but this is not a good way to build React components. You should use memory only if the component meets the following conditions:

  • Returns the same output when given the same props
  • Has multiple UI elements and virtual DOM checking affects performance
  • The same props are often provided

Summary

In this tutorial, we have seen:

  • How to render UI with React
  • Why do I need to remember
  • How to achieve memory in React by React.memo() for functional React components and React.PureComponent as class components
  • React.memo()A use case, even after using
  • , the child component will be rerendered
  • useCallback()How to use
  • hook to avoid re-rendering when passing a function as props to a child component.

I hope you find this introduction to React memory useful!

FAQs about React Memorization

(This is similar to the original text, but some adjustments have been made to the language and expression.)

The above is the detailed content of How to Implement Memoization in React to Improve Performance. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

var vs let vs const: a quick JS roundup explainer var vs let vs const: a quick JS roundup explainer Jul 02, 2025 am 01:18 AM

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

Why is DOM manipulation slow and how can it be optimized? Why is DOM manipulation slow and how can it be optimized? Jul 01, 2025 am 01:28 AM

The main reasons for slow operation of DOM are the high cost of rearrangement and redrawing and low access efficiency. Optimization methods include: 1. Reduce the number of accesses and cache read values; 2. Batch read and write operations; 3. Merge and modify, use document fragments or hidden elements; 4. Avoid layout jitter and centrally handle read and write; 5. Use framework or requestAnimationFrame asynchronous update.

See all articles