<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: liu-jin-yi</title>
    <description>The latest articles on Forem by liu-jin-yi (@liujinyi).</description>
    <link>https://forem.com/liujinyi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F702134%2F3d5cdb4a-62e3-4624-b22a-ace48b0052a6.jpeg</url>
      <title>Forem: liu-jin-yi</title>
      <link>https://forem.com/liujinyi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/liujinyi"/>
    <language>en</language>
    <item>
      <title>🔥🔥🔥  Introducing ESBuild, compiling is straight up fast!!!</title>
      <dc:creator>liu-jin-yi</dc:creator>
      <pubDate>Fri, 05 Nov 2021 08:17:28 +0000</pubDate>
      <link>https://forem.com/liujinyi/introducing-esbuild-compiling-is-straight-up-fast-59n7</link>
      <guid>https://forem.com/liujinyi/introducing-esbuild-compiling-is-straight-up-fast-59n7</guid>
      <description>&lt;p&gt;The current hands of the project hot update is getting slower and slower, so there is the emergence of this piece of article, this is a tutorial article, the current set has come up the company's development environment, this example is the previous experiment to test and do. This piece of tutorial code and the real introduction of the project code or a certain difference, if the partners also want to introduce esbuild packaging for the company's project, you can leave a comment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Since the company's project is an old one, I mainly addressed the experience of working in a development environment.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  🔥 Creating a basic CRA project
&lt;/h2&gt;

&lt;p&gt;Let's start by creating a basic react project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn create react-app my-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Preview Folder&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F709749d2773b4468bed37e3cef8c3967~tplv-k3u1fbpfcp-watermark.image%3F" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F709749d2773b4468bed37e3cef8c3967~tplv-k3u1fbpfcp-watermark.image%3F" alt="2021-10-16 15.17.42.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After creating the test project let's see what problems we have to solve to introduce esbuild?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We need a &lt;strong&gt;local server&lt;/strong&gt;, that will display the packaged files.&lt;/li&gt;
&lt;li&gt;A library &lt;strong&gt;for parsing command line arguments is also needed&lt;/strong&gt;, to pass variables for the development environment.&lt;/li&gt;
&lt;li&gt;It is also necessary to delete the last packed file every time you start the project.&lt;/li&gt;
&lt;li&gt;There is also a need to address the &lt;strong&gt;port number&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Solve &lt;strong&gt;svg's icon&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Introduce esbuild for packaging.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;With the above problem solved, we can implement this demo.&lt;/p&gt;

&lt;h2&gt;
  
  
  🔥 Download Dependency Packages
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add browser-sync --dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The main purpose of this package is to create the server, render the packaged files, and listen for file changes in the specified file for esbuild to repackage.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add chalk --dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The main purpose of this package is to beautify the character style of the terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add command-line-args --dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a library mainly used for parsing command line arguments and we mainly use it to confirm if it is a development environment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add del --dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We mainly use this package to perform deletion operations on packed files or folders.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add get-port@5.1.1 --dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use this library mainly to get the current TCP port number available. I didn't install the latest version because the latest version has requirements for Node.js, my node version is v12.18.3, and it's expected node version is: "^12.20.0 || ^14.13.1 || &amp;gt;=16.0.0".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;We copy the public folder and rename it to public-dev, the index.html in this folder is the entry point of our application.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add --dev esbuild-plugin-svgr
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Plugin for esbuild that adds support for importing &lt;code&gt;*.svg&lt;/code&gt; files as React components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add esbuild --dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last thing is to install esbuild.&lt;/p&gt;

&lt;h2&gt;
  
  
  🔥 Modification package.json
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    "scripts": {
        ...
+++     "dev": "node devBuild.js --dev"
      },
      ...
+++ "type": "module"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  🔥 Create devBuild.js
&lt;/h2&gt;

&lt;p&gt;After changing the package.json file, next create devBuild.js in the root folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import browserSync from "browser-sync";
import chalk from "chalk";
import commandLineArgs from "command-line-args";
import del from "del";
import esbuild from "esbuild";
import getPort from "get-port";
import svgrPlugin from "esbuild-plugin-svgr";
// Create the server.
const bs = browserSync.create();
// Deconstructing environment variables
const { dev } = commandLineArgs({ name: "dev", type: Boolean });
// Delete the package folder from the public-dev folder
del.sync("./public-dev/dist");

// Start esbuild to build the package
(async () =&amp;gt; {
  const buildResult = await esbuild
    .build({
      format: "esm", // Sets the output format of the generated JavaScript file.
      target: "es2017", // Compile to convert version
      entryPoints: ["./src/index.jsx"], // Packed Entrance
      outdir: "./public-dev/dist", // Output Directory
      chunkNames: "chunks/[name].[hash]", // Packed out file name
      incremental: dev, // Because we are listening for file changes to repack, and we want the development environment to use esbuild, dev is true.
      loader: {
        // This option changes the way the given input file is interpreted.
        ".svg": "text",
        ".png": "dataurl",
      },
      bundle: true, // Bundling files means inlining any imported dependencies into the file itself.
      splitting: true, // Code splitting is currently only available for esm output format.
      plugins: [svgrPlugin()],
      inject: ["./public-dev/react-shim.js"], // Import React into esbuild as a global variable
    })
    .catch((err) =&amp;gt; {
      console.error(chalk.red(err));
      process.exit(1);
    });
  console.log(chalk.green("The build has finished! 📦\n"));
  // Get the port number that can be used
  const port = await getPort({
    port: getPort.makeRange(4000, 4999),
  });

  console.log(
    chalk.cyan(
      `Launching the Shoelace dev server at http://localhost:${port}! 🥾\n`
    )
  );
  // Server initialization
  bs.init({
    startPath: "/", // Initial path
    port, // Port number
    logLevel: "silent", // Log level
    logFileChanges: true, // Log file changes
    notify: true, // Small pop-up notifications in the browser
    single: true, // Provide separate index.html
    server: {
      baseDir: "public-dev", // Base Folder
      index: "index.html", // Set the server's entry file
    },
    files: "src/", // Listening to files under src
  });

  // Listening for changes under the src folder
  bs.watch(["src/"]).on("change", async (filename) =&amp;gt; {
    console.log(`Source file changed - ${filename}`);
    // Repackaging
    buildResult.rebuild();
  });
})();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  🔥 index.html
&lt;/h2&gt;

&lt;p&gt;Because I didn't want to change things directly under the public file, I directly copied the public folder and renamed it to public-dev. Why did I do that? Mainly because I didn't want to intersect with the webpack packaged files. So I simply copied a folder directly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In the index.html file, we have to introduce the packaged css and js. Here we have to be careful when introducing the js, we must use the ESM way to introduce it. Otherwise it will report an error!!!&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;

&amp;lt;head&amp;gt;
  &amp;lt;meta charset="utf-8" /&amp;gt;
  &amp;lt;link rel="icon" href="%PUBLIC_URL%/favicon.ico" /&amp;gt;
  &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1" /&amp;gt;
  &amp;lt;meta name="theme-color" content="#000000" /&amp;gt;
  &amp;lt;meta name="description" content="Web site created using create-react-app" /&amp;gt;
  &amp;lt;link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /&amp;gt;
  &amp;lt;link rel="manifest" href="%PUBLIC_URL%/manifest.json" /&amp;gt;
++  &amp;lt;link rel="stylesheet" type="text/css" href="./dist/index.css" /&amp;gt;
  &amp;lt;title&amp;gt;React App&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
  &amp;lt;noscript&amp;gt;You need to enable JavaScript to run this app.&amp;lt;/noscript&amp;gt;
  &amp;lt;div id="root"&amp;gt;&amp;lt;/div&amp;gt;
++  &amp;lt;script type="module"&amp;gt;
++    import './dist/index.js'
++  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;

&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Change the component suffix name to &lt;code&gt;.jsx&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  🔥 react-shim.js
&lt;/h2&gt;

&lt;p&gt;The main purpose of creating this file is to import React into esbuild as a global variable, so that you don't need to introduce react in each component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as React from "react";
export { React };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  🔥 Modify App.jsx
&lt;/h2&gt;

&lt;p&gt;The main thing here is that the usage of svg needs to be changed. This is because the usage of the plugin &lt;code&gt;esbuild-plugin-svgr&lt;/code&gt; has to be conformed to.&lt;/p&gt;

&lt;p&gt;It is also crucial to &lt;strong&gt;change the suffix name of all components with the previous js to jsx.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;++ import Logo from "./logo.svg";
import "./App.css";

function App() {
  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;header className="App-header"&amp;gt;
++        &amp;lt;Logo className="App-logo" /&amp;gt;
        &amp;lt;p&amp;gt;
          Edit &amp;lt;code&amp;gt;src/App.js&amp;lt;/code&amp;gt; and save to reload.
        &amp;lt;/p&amp;gt;
        &amp;lt;a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        &amp;gt;
          Learn React
        &amp;lt;/a&amp;gt;
      &amp;lt;/header&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point, introducing esbuild in CRA is Ok! If you are interested, go ahead and try it!&lt;/p&gt;

&lt;h2&gt;
  
  
  🔥  Preview demo
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F1a369b6a62b140e5b2fe280fda8eb693~tplv-k3u1fbpfcp-watermark.image%3F" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F1a369b6a62b140e5b2fe280fda8eb693~tplv-k3u1fbpfcp-watermark.image%3F" alt="2021-10-16 18.29.06.gif"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>vue</category>
    </item>
    <item>
      <title>🔥 🔥 🔥 Do you know all these means to avoid repeated rendering of React components?</title>
      <dc:creator>liu-jin-yi</dc:creator>
      <pubDate>Sun, 31 Oct 2021 06:11:21 +0000</pubDate>
      <link>https://forem.com/liujinyi/do-you-know-all-these-means-to-avoid-repeated-rendering-of-react-components-5mf</link>
      <guid>https://forem.com/liujinyi/do-you-know-all-these-means-to-avoid-repeated-rendering-of-react-components-5mf</guid>
      <description>&lt;p&gt;Use React has been three years, in these three years inside also deposited a lot of best practices on React code optimization, today first write a part out and share with you to share. We'll see if the article is popular and then we'll see if we share the later ones.&lt;/p&gt;

&lt;p&gt;For each best practice in this post I will provide two examples, one good and one bad, for comparison, and a preview of the &lt;code&gt;.gif&lt;/code&gt; image.&lt;/p&gt;

&lt;p&gt;The article in this piece focuses on optimizing these three situations：&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Parent component update causes child component to render&lt;/li&gt;
&lt;li&gt;Wrong way of writing Props leads to component rendering&lt;/li&gt;
&lt;li&gt;Context updates lead to component rendering&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After reading the article if you think it has helped you, please help to click a praise, your praise is the biggest motivation for my creation. &lt;strong&gt;comment kudos can get the source code!!!&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Parent component update causes child component to render
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Class Example
&lt;/h3&gt;

&lt;h4&gt;
  
  
  ❎ Error Example Preview
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2Fa35acb5e75a64b1ca1ee523e1501d063~tplv-k3u1fbpfcp-watermark.image%3F" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2Fa35acb5e75a64b1ca1ee523e1501d063~tplv-k3u1fbpfcp-watermark.image%3F" alt="1.classBad.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ❎ Error Example
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from "react";
class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  handleClick = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };
  render() {
    const { count } = this.state;
    return (
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Error Example&amp;lt;/h5&amp;gt;
        &amp;lt;p&amp;gt;Parent ComponentCount--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={this.handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
        &amp;lt;Son /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

class Son extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    console.log("Sub-component re-rendered!!!");
    return &amp;lt;div className="son"&amp;gt;Sub-components&amp;lt;/div&amp;gt;;
  }
}

export { Parent, Son };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, a change in the state of the parent component causes the child component to be re-rendered, which is a very normal way to write code, but seriously, it will still cause a waste of performance, after all, the child component is re-rendered! Next, let's see how to solve this problem!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: This example does not mean to eliminate the need to write such code, in fact, optimization is also dependent on the scenario!&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 1
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, PureComponent } from "react";
class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  handleClick = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };
  render() {
    const { count } = this.state;
    return (
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Correct example 1&amp;lt;/h5&amp;gt;
        &amp;lt;p&amp;gt;Parent ComponentCount--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={this.handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
        &amp;lt;Son /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

class Son extends PureComponent {
  constructor(props) {
    super(props);
  }
  render() {
    console.log("Sub-component re-rendered!!!");
    return &amp;lt;div className="son"&amp;gt;Sub-components&amp;lt;/div&amp;gt;;
  }
}

export default Parent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example we are mainly borrowing from &lt;strong&gt;PureComponent&lt;/strong&gt; to inherit this class, and React will automatically perform &lt;strong&gt;shouldComponentUpdate&lt;/strong&gt; for us to perform a shallow comparison optimization update of Props.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: Actually, in all seriousness, components in React are executed by React.createElement(Son), and the resulting component's Props reference is new every time, thus triggering a re-render!&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 2
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from "react";
class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  handleClick = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };
  render() {
    const { count } = this.state;
    const { children } = this.props;
    return (
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Correct example 2&amp;lt;/h5&amp;gt;
        &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={this.handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
        {children}
      &amp;lt;/div&amp;gt;
    );
  }
}

export default Parent;

&amp;lt;Parent&amp;gt;
  &amp;lt;Son /&amp;gt;
&amp;lt;/Parent&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the optimization of this example, we separate stateful and stateless components and use &lt;strong&gt;children&lt;/strong&gt; to pass stateless components in. This will avoid pointless re-rendering! So why would writing it this way avoid re-rendering? Because using &lt;br&gt;
 &lt;strong&gt;children&lt;/strong&gt; directly in the stateful component will avoid using &lt;strong&gt;React.createElement(Son)&lt;/strong&gt; to render the child component in the stateful component! This can also be done to optimize!&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 3
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, memo } from "react";
import { Son } from "./Bad";

const MemoSon = memo(() =&amp;gt; &amp;lt;Son&amp;gt;&amp;lt;/Son&amp;gt;);

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  handleClick = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };
  render() {
    const { count } = this.state;
    return (
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Correct example 3&amp;lt;/h5&amp;gt;
        &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={this.handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
        &amp;lt;MemoSon /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export default Parent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, the idea of optimization is similar to the one mentioned in example 1, we borrowed the &lt;strong&gt;memo&lt;/strong&gt; function, which is actually an optimization tool for the &lt;strong&gt;Function component&lt;/strong&gt; We are also cheeky here to force the use of a little! The idea of avoiding re-rendering is actually to compare references to Props as well. Decide whether to render or not !!!&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 4
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, useState, Fragment } from "react";
import { Son } from "./Bad";

const ClickCount = () =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = () =&amp;gt; {
    setCount((old) =&amp;gt; old + 1);
  };
  return (
    &amp;lt;Fragment&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;h5&amp;gt;Correct example 4&amp;lt;/h5&amp;gt;
        &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/Fragment&amp;gt;
  );
};

class Parent extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;ClickCount /&amp;gt;
        &amp;lt;Son /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export default Parent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, our optimization is mainly to remove the state component into one component, so that the state change is separated from the child component. It also avoids the re-rendering of the child components!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Description: This optimization means seriously speaking or used quite little, depending on the situation use it!&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Hooks Example
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Error Example Preview
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F0970a11548c54714a7df5718eac2cce6~tplv-k3u1fbpfcp-watermark.image%3F" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F0970a11548c54714a7df5718eac2cce6~tplv-k3u1fbpfcp-watermark.image%3F" alt="1.HooksBad.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ❎ Error Example
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from "react";
const Son = () =&amp;gt; {
  console.log("Sub-component re-rendered!!!");
  return &amp;lt;div className="son"&amp;gt;Sub-components&amp;lt;/div&amp;gt;;
};

const Parent = () =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = () =&amp;gt; {
    setCount((old) =&amp;gt; old + 1);
  };
  return (
    &amp;lt;div className="parent"&amp;gt;
      &amp;lt;h5&amp;gt;Error Example&amp;lt;/h5&amp;gt;
      &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;Son /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export { Son, Parent };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For Hooks the above is also a very normal way of writing, but compared to Class components, &lt;strong&gt;Function components&lt;/strong&gt; have the feature that each time the component is re-rendered, the function is re-executed once. For a Class component, it will only execute &lt;strong&gt;new Class&lt;/strong&gt; once, which is actually quite scary when you think about it. For function components, each execution means a new context, a new variable, and a new scope. So we need to pay more attention to the performance optimization of function components.&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 1
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from "react";

const Parent = ({ children }) =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = () =&amp;gt; {
    setCount((old) =&amp;gt; old + 1);
  };
  return (
    &amp;lt;div className="parent"&amp;gt;
      &amp;lt;h5&amp;gt;Correct example 1&amp;lt;/h5&amp;gt;
      &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
      {children}
    &amp;lt;/div&amp;gt;
  );
};

export default Parent;

&amp;lt;Parent&amp;gt;
  &amp;lt;Son /&amp;gt;
&amp;lt;/Parent

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, we use &lt;strong&gt;children&lt;/strong&gt; to render child components directly, the principle of which has been explained in the Class component example above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Description: Seriously speaking, combining the characteristics of function components this means of optimization is actually a cure for the symptoms, not the root cause!&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 2
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useMemo } from "react";
import { Son } from "./Bad";
const Parent = () =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = () =&amp;gt; {
    setCount((old) =&amp;gt; old + 1);
  };
  return (
    &amp;lt;div className="parent"&amp;gt;
      &amp;lt;h5&amp;gt;Correct example 2&amp;lt;/h5&amp;gt;
      &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
      {useMemo(
        () =&amp;gt; (
          &amp;lt;Son /&amp;gt;
        ),
        []
      )}
    &amp;lt;/div&amp;gt;
  );
};

export default Parent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;n this example we use the optimization Hook &lt;strong&gt;useMemo&lt;/strong&gt; , we cache the Son component and only when the dependency changes we re-execute the function to complete the re-rendering, otherwise the timing is the same &lt;strong&gt;memoized&lt;/strong&gt;, which helps avoid high overhead calculations at each rendering. It also avoids having to redeclare variables, functions, scopes, etc. in the child component each time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: I think this optimization is absolutely brilliant because useMemo saves the component reference and does not re-execute the function component, thus avoiding the declaration of variables, functions, and scopes within the component. Thus, performance is optimized. Nice!&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 3
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, memo } from "react";
import { Son } from "./Bad";

const SonMemo = memo(Son);

const Parent = () =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = () =&amp;gt; {
    setCount((old) =&amp;gt; old + 1);
  };
  return (
    &amp;lt;div className="parent"&amp;gt;
      &amp;lt;h5&amp;gt;Correct example 3&amp;lt;/h5&amp;gt;
      &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;SonMemo /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Parent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example we use the api &lt;strong&gt;memo&lt;/strong&gt;, mainly to compare whether the props reference has changed, thus avoiding the re-rendering of child components!&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrong way of writing Props leads to component rendering
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Class Example
&lt;/h3&gt;

&lt;h4&gt;
  
  
  ❎ Error Example Preview
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F1d31e1ec190a42a8bb3b81f5b4df9da9~tplv-k3u1fbpfcp-watermark.image%3F" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp3-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F1d31e1ec190a42a8bb3b81f5b4df9da9~tplv-k3u1fbpfcp-watermark.image%3F" alt="2.ClassBad.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ❎ Error Example
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, PureComponent } from "react";

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  handleClick = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };
  render() {
    const { count } = this.state;
    return (
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Error Example&amp;lt;/h5&amp;gt;
        &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={this.handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
        &amp;lt;Son componentDetails={{ name: "Sub-components" }} anyMethod={() =&amp;gt; {}} /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

class Son extends PureComponent {
  constructor(props) {
    super(props);
  }
  render() {
    const { componentDetails, anyMethod } = this.props;
    console.log("Son -&amp;gt; render -&amp;gt; anyMethod", anyMethod);
    console.log("Son -&amp;gt; render -&amp;gt; componentDetails", componentDetails);
    return &amp;lt;div className="son"&amp;gt;{componentDetails?.name}&amp;lt;/div&amp;gt;;
  }
}

export { Parent, Son };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The passing of Props in this example is directly wrong way to write it. Because the rendering of the component is mainly rendered by listening to the change of Props and State, that in this example passed props each time is a new object,*&lt;em&gt;because the reference is different, each time the rendering of the parent component will lead to the rendering of the child component. *&lt;/em&gt; So the re-rendering of real numbers caused by this writing should not!&lt;/p&gt;

&lt;p&gt;So how should we write it?&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 1
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, PureComponent } from "react";

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      componentDetails: { name: "Sub-components" },
    };
  }
  handleClick = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };
  anyMethod = () =&amp;gt; {};
  render() {
    const { count, componentDetails } = this.state;
    return (
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Correct example 1&amp;lt;/h5&amp;gt;
        &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={this.handleClick}&amp;gt;增加&amp;lt;/button&amp;gt;
        &amp;lt;Son componentDetails={componentDetails} anyMethod={this.anyMethod} /&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

class Son extends PureComponent {
  constructor(props) {
    super(props);
  }
  render() {
    const { componentDetails, anyMethod } = this.props;
    console.log("Son -&amp;gt; render -&amp;gt; anyMethod", anyMethod);
    console.log("Son -&amp;gt; render -&amp;gt; componentDetails", componentDetails);
    return &amp;lt;div className="son"&amp;gt;{componentDetails?.name}&amp;lt;/div&amp;gt;;
  }
}

export default Parent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The main correct way to write this example is to pass the variable directly to the child component, because the reference to the variable is the same, so after checking by &lt;strong&gt;PureComponent&lt;/strong&gt;, the reference has not changed, thus preventing the child component from rendering!!!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: Strictly speaking, this buggy example is a writing problem that causes re-rendering of subcomponents, so there's no talk of optimization, so let's forbid writing code like the buggy example!&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Hooks Example
&lt;/h3&gt;

&lt;h4&gt;
  
  
  ❎ Error Example Preview
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp1-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2Fb7bb39ef843e492ab780e9d29430e146~tplv-k3u1fbpfcp-watermark.image%3F" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp1-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2Fb7bb39ef843e492ab780e9d29430e146~tplv-k3u1fbpfcp-watermark.image%3F" alt="2.HooksBad.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ❎ Error Example
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from "react";
const Son = ({ componentDetails, anyMethod }) =&amp;gt; {
  useEffect(() =&amp;gt; {
    console.log("Son -&amp;gt; componentDetails", componentDetails);
  }, [componentDetails]);
  useEffect(() =&amp;gt; {
    console.log("Son -&amp;gt; anyMethod", anyMethod);
  }, [anyMethod]);
  return &amp;lt;div className="son"&amp;gt;{componentDetails.name}&amp;lt;/div&amp;gt;;
};

const Parent = () =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = () =&amp;gt; {
    setCount((old) =&amp;gt; old + 1);
  };
  return (
    &amp;lt;div className="parent"&amp;gt;
      &amp;lt;h5&amp;gt;Error Example&amp;lt;/h5&amp;gt;
      &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;Son componentDetails={{ name: "Sub-components" }} anyMethod={() =&amp;gt; {}} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export { Son, Parent };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this error example, it is still a problem with the way props are passed! Next see how to correct it!&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 1
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from "react";
const Son = ({ componentDetails, anyMethod }) =&amp;gt; {
  useEffect(() =&amp;gt; {
    console.log("Son -&amp;gt; componentDetails", componentDetails);
  }, [componentDetails]);
  useEffect(() =&amp;gt; {
    console.log("Son -&amp;gt; anyMethod", anyMethod);
  }, [anyMethod]);
  return &amp;lt;div className="son"&amp;gt;{componentDetails.name}&amp;lt;/div&amp;gt;;
};
// This is written for immutable values and can be passed like this
const componentDetails = { name: "Sub-components件" };
const anyMethod = () =&amp;gt; {};

const Parent = () =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = () =&amp;gt; {
    setCount((old) =&amp;gt; old + 1);
  };
  return (
    &amp;lt;div className="parent"&amp;gt;
      &amp;lt;h5&amp;gt;Correct example 1&amp;lt;/h5&amp;gt;
      &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;Son componentDetails={componentDetails} anyMethod={anyMethod} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Parent;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, we simply refer the invariant value &lt;strong&gt;outside the component&lt;/strong&gt; to ensure that the reference is unique and will not change as the component is updated. But there is a limitation to this way of writing. It is that it is only suitable for invariant values. But it also effectively avoids duplicate rendering of components.&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 2
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect, useMemo, useCallback } from "react";
const Son = ({ componentDetails, anyMethod }) =&amp;gt; {
  useEffect(() =&amp;gt; {
    console.log("Son -&amp;gt; componentDetails", componentDetails);
  }, [componentDetails]);
  useEffect(() =&amp;gt; {
    console.log("Son -&amp;gt; anyMethod", anyMethod);
  }, [anyMethod]);
  return &amp;lt;div className="son"&amp;gt;{componentDetails.name}&amp;lt;/div&amp;gt;;
};

const Parent = () =&amp;gt; {
  const [count, setCount] = useState(0);
  const handleClick = () =&amp;gt; {
    setCount((old) =&amp;gt; old + 1);
  };

  const anyMethod = useCallback(() =&amp;gt; {}, []);

  const [componentDetails] = useMemo(() =&amp;gt; {
    const componentDetails = { name: "Sub-components" };
    return [componentDetails];
  }, []);

  return (
    &amp;lt;div className="parent"&amp;gt;
      &amp;lt;h5&amp;gt;Correct example 2&amp;lt;/h5&amp;gt;
      &amp;lt;p&amp;gt;Parent Component Count--{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;Son componentDetails={componentDetails} anyMethod={anyMethod} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Parent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, two optimization hooks, &lt;strong&gt;useCallback&lt;/strong&gt; and  &lt;strong&gt;useMemo&lt;/strong&gt; , are used to determine whether to update a value change based on whether the dependency has changed to ensure that the value reference remains unchanged. This is suitable for most writes, but it should not be overused. Otherwise the code will be very confusing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Context updates lead to component rendering
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Class Example
&lt;/h3&gt;

&lt;h4&gt;
  
  
  ❎ Error Example Preview
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp1-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2Fb15006e4a38d4327ab68b10e2bd1b270~tplv-k3u1fbpfcp-watermark.image%3F" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp1-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2Fb15006e4a38d4327ab68b10e2bd1b270~tplv-k3u1fbpfcp-watermark.image%3F" alt="3.ClassBad.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ❎ Error Example
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, createContext } from "react";

const contextValue = createContext(undefined);

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      handleIncrement:this.handleIncrement
    };
  }
  handleIncrement = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };

  render() {


    return (
      &amp;lt;contextValue.Provider
        value={this.state}
      &amp;gt;
        &amp;lt;div className="parent"&amp;gt;
          &amp;lt;h5&amp;gt;Error Example&amp;lt;/h5&amp;gt;
          &amp;lt;Son1 /&amp;gt;
          &amp;lt;contextValue.Consumer&amp;gt;
            {(conProps) =&amp;gt; &amp;lt;Son2 conProps={conProps} /&amp;gt;}
          &amp;lt;/contextValue.Consumer&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/contextValue.Provider&amp;gt;
    );
  }
}

class Son1 extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    console.log("Subcomponent 1 is re-rendered!");
    return &amp;lt;div className="son"&amp;gt;Subassembly 1&amp;lt;/div&amp;gt;;
  }
}

class Son2 extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    console.log("Subcomponent 2 is re-rendered!");

    const {
      conProps: { count, handleIncrement },
    } = this.props;
    return (
      &amp;lt;div className="son"&amp;gt;
        &amp;lt;p&amp;gt;Subassembly 2--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={handleIncrement}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export { Parent };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, if you look carefully, when you click the button in child component 2,&lt;strong&gt;t is the state of the parent component that changes&lt;/strong&gt; so the problem is that the rendering of the parent component causes the child component to render as well. So how should we avoid duplicate rendering of the child component?&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 1
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, createContext } from "react";

const contextValue = createContext(undefined);

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      handleIncrement:this.handleIncrement
    };
  }
  handleIncrement = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };

  render() {
    const { children } = this.props;
    return (
      &amp;lt;contextValue.Provider
        value={this.state}
      &amp;gt;
        &amp;lt;div className="parent"&amp;gt;
          &amp;lt;h5&amp;gt;Correct example 1&amp;lt;/h5&amp;gt;
          {children}
          &amp;lt;contextValue.Consumer&amp;gt;
            {(conProps) =&amp;gt; &amp;lt;Son2 conProps={conProps} /&amp;gt;}
          &amp;lt;/contextValue.Consumer&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/contextValue.Provider&amp;gt;
    );
  }
}

class Son1 extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    console.log("Subcomponent 1 is re-rendered!");
    return &amp;lt;div className="son"&amp;gt;Subassembly 1&amp;lt;/div&amp;gt;;
  }
}

class Son2 extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    console.log("Subcomponent 2 is re-rendered!");

    const {
      conProps: { count, handleIncrement },
    } = this.props;
    return (
      &amp;lt;div className="son"&amp;gt;
        &amp;lt;p&amp;gt;Subassembly 2--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={handleIncrement}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export { Parent, Son1 };

&amp;lt;Parent&amp;gt;
 &amp;lt;Son1 /&amp;gt;
&amp;lt;/Parent&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, we still borrow the mechanism of &lt;strong&gt;children&lt;/strong&gt; o render directly, so there is no &lt;strong&gt;Ract.createElement(Son)&lt;/strong&gt; api execution in the parent component, and therefore no duplicate rendering!&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 2
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, createContext, PureComponent } from "react";

const contextValue = createContext(undefined);

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      handleIncrement:this.handleIncrement
    };
  }
  handleIncrement = () =&amp;gt; {
    const { count } = this.state;
    this.setState({
      count: count + 1,
    });
  };

  render() {
    return (
      &amp;lt;contextValue.Provider
        value={this.state}
      &amp;gt;
        &amp;lt;div className="parent"&amp;gt;
          &amp;lt;h5&amp;gt;Correct example 2&amp;lt;/h5&amp;gt;
          &amp;lt;Son1 /&amp;gt;
          &amp;lt;contextValue.Consumer&amp;gt;
            {(conProps) =&amp;gt; &amp;lt;Son2 conProps={conProps} /&amp;gt;}
          &amp;lt;/contextValue.Consumer&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/contextValue.Provider&amp;gt;
    );
  }
}

class Son1 extends PureComponent {
  constructor(props) {
    super(props);
  }
  render() {
    console.log("Subcomponent 1 is re-rendered!");
    return &amp;lt;div className="son"&amp;gt;Subcomponent 1&amp;lt;/div&amp;gt;;
  }
}

class Son2 extends PureComponent {
  constructor(props) {
    super(props);
  }
  render() {
    console.log("Subcomponent 2 is re-rendered!");

    const {
      conProps: { count, handleIncrement },
    } = this.props;
    return (
      &amp;lt;div className="son"&amp;gt;
        &amp;lt;p&amp;gt;Subcomponent 2--{count}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={handleIncrement}&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export default Parent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, we mainly borrow the class &lt;strong&gt;PureComponent&lt;/strong&gt; to help us perform the optimization automatically, so it is also possible to avoid duplicate rendering.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: Here you can also force the use of React.memo a bit.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Hooks Example
&lt;/h3&gt;

&lt;h4&gt;
  
  
  ❎ Error Example Preview
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp9-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F69380ea1d85e49a9b624e35b4abebc45~tplv-k3u1fbpfcp-watermark.image%3F" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fp9-juejin.byteimg.com%2Ftos-cn-i-k3u1fbpfcp%2F69380ea1d85e49a9b624e35b4abebc45~tplv-k3u1fbpfcp-watermark.image%3F" alt="3.HooksBad.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ❎ Error Example
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createContext, useContext } from "react";
import { useCustomReducer } from "../useCustomizeContext";
const CustomizeContext = createContext(undefined);

const Son1 = () =&amp;gt; {
  console.log("Subcomponent 1 re-rendered!!!");
  return &amp;lt;div className="son"&amp;gt;子组件1&amp;lt;/div&amp;gt;;
};
const Son2 = () =&amp;gt; {
  const { count, handleIncrement } = useContext(CustomizeContext);
  console.log("Subcomponent 2 re-rendered!!!");
  return (
    &amp;lt;div className="son"&amp;gt;
      &amp;lt;p&amp;gt;Subcomponent 2-{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleIncrement}&amp;gt;Add&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

const Parent = () =&amp;gt; {
  const value = useCustomReducer({ initValue: 1 });
  return (
    &amp;lt;CustomizeContext.Provider value={value}&amp;gt;
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Error Example&amp;lt;/h5&amp;gt;
        &amp;lt;Son2 /&amp;gt;
        &amp;lt;Son1 /&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/CustomizeContext.Provider&amp;gt;
  );
};

export { Son1, Parent, Son2 };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, the api's  &lt;strong&gt;createContext，useContext，useReducer&lt;/strong&gt; are used to implement a small Redux, and clicking on the button in child component 2 changes the count value, which in turn causes the value to change, so the parent component renders, causing the child component to follow suit.&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 1
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import {
  CustomizeProvider,
  useCustomizeContext,
  useCustomReducer,
} from "../useCustomizeContext";

const Son1 = () =&amp;gt; {
  console.log("Subcomponent 1 re-rendered!!!");
  return &amp;lt;div className="son"&amp;gt;Subcomponent 1&amp;lt;/div&amp;gt;;
};
const Son2 = () =&amp;gt; {
  const { count, handleIncrement } = useCustomizeContext();
  console.log("Subcomponent 2 re-rendered!!!");
  return (
    &amp;lt;div className="son"&amp;gt;
      &amp;lt;p&amp;gt;Subcomponent 2-{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleIncrement}&amp;gt;Add&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

const Parent = ({ children }) =&amp;gt; {
  const value = useCustomReducer({ initValue: 1 });
  return (
    &amp;lt;CustomizeProvider value={value}&amp;gt;
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Correct example 1&amp;lt;/h5&amp;gt;
        &amp;lt;Son2 /&amp;gt;
        {children}
      &amp;lt;/div&amp;gt;
    &amp;lt;/CustomizeProvider&amp;gt;
  );
};
export { Son1 };
export default Parent;


&amp;lt;Parent&amp;gt;
 &amp;lt;Son1 /&amp;gt;
&amp;lt;/Parent&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example we are still using &lt;strong&gt;children&lt;/strong&gt; to solve the duplicate rendering problem. This still works!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Description: In fact, you must use the right optimization in your project!&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct example 2
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { memo } from "react";
import {
  CustomizeProvider,
  useCustomizeContext,
  useCustomReducer,
} from "../useCustomizeContext";

const Son1 = () =&amp;gt; {
  console.log("Subcomponent 1 re-rendered!!!");
  return &amp;lt;div className="son"&amp;gt;Subcomponent 1&amp;lt;/div&amp;gt;;
};
const Son2 = () =&amp;gt; {
  const { count, handleIncrement } = useCustomizeContext();
  console.log("Subcomponent 2 re-rendered!!!");
  return (
    &amp;lt;div className="son"&amp;gt;
      &amp;lt;p&amp;gt;Subcomponent 2-{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleIncrement}&amp;gt;Add&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
// use memo
const MemoSon1 = memo(Son1);
const Parent = () =&amp;gt; {
  const value = useCustomReducer({ initValue: 1 });
  return (
    &amp;lt;CustomizeProvider value={value}&amp;gt;
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Correct example 2&amp;lt;/h5&amp;gt;
        &amp;lt;Son2 /&amp;gt;
        &amp;lt;MemoSon1 /&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/CustomizeProvider&amp;gt;
  );
};

export default Parent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The api &lt;strong&gt;memo&lt;/strong&gt; is also used in this example, and is still the same, comparing whether the reference to the props has changed or not, and deciding whether to update it or not.&lt;/p&gt;

&lt;h4&gt;
  
  
  ✅ Correct Example 3
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useMemo } from "react";
import {
  CustomizeProvider,
  useCustomizeContext,
  useCustomReducer,
} from "../useCustomizeContext";

const Son1 = () =&amp;gt; {
  console.log("Subcomponent 1 re-rendered!!!");
  return &amp;lt;div className="son"&amp;gt;Subcomponent 1&amp;lt;/div&amp;gt;;
};
const Son2 = () =&amp;gt; {
  const { count, handleIncrement } = useCustomizeContext();
  console.log("Subcomponent 2 re-rendered!!!");
  return (
    &amp;lt;div className="son"&amp;gt;
      &amp;lt;p&amp;gt;Subcomponent 2-{count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={handleIncrement}&amp;gt;Add&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

const Parent = () =&amp;gt; {
  const value = useCustomReducer({ initValue: 1 });
  return (
    &amp;lt;CustomizeProvider value={value}&amp;gt;
      &amp;lt;div className="parent"&amp;gt;
        &amp;lt;h5&amp;gt;Correct Example 3&amp;lt;/h5&amp;gt;
        &amp;lt;Son2 /&amp;gt;
        {useMemo(
          () =&amp;gt; (
            &amp;lt;Son1 /&amp;gt;
          ),
          []
        )}
      &amp;lt;/div&amp;gt;
    &amp;lt;/CustomizeProvider&amp;gt;
  );
};

export default Parent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://codesandbox.io/s/react-code-best-practices-lzf1o" rel="noopener noreferrer"&gt;✋🏻 Click to view online demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example we still use the &lt;strong&gt;useMemo&lt;/strong&gt; optimization hook to optimize the component.&lt;/p&gt;

&lt;h2&gt;
  
  
  🤙🤙🤙 Summary
&lt;/h2&gt;

&lt;p&gt;The means of optimization in three cases are described in the article of this piece, mainly the use of.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;🤙useMemo&lt;/li&gt;
&lt;li&gt;🤙memo&lt;/li&gt;
&lt;li&gt;🤙children&lt;/li&gt;
&lt;li&gt;🤙useCallback&lt;/li&gt;
&lt;li&gt;🤙PureComponent&lt;/li&gt;
&lt;li&gt;🤙Extracting status components&lt;/li&gt;
&lt;li&gt;🤙Extraction of constant values&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These optimizations can be used in different situations, so you must use the appropriate optimizations if you are in the process of using them in conjunction with your code. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you know other means of optimization can also be left in the comments section Oh!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
