React method to prevent child components from rendering: 1. Use "shouldComponentUpdate(nextProps,nextState){...}" to achieve parent component rendering and child components not to render; 2. Use "PureComponent" to prevent child components from rendering. The component does not render; 3. Introduce memo and wrap the hooks with memo.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to prevent child components from rendering in react?
React parent component re-renders and child components do not need to be rendered. Three performance optimization methods (PureComponent, memo, shouldComponentUpdate);
//When using React ordinary functions, you can use Two optimization methods, PureComponent and shouldComponentUpdate
//shouldComponentUpdate
//shouldComponentUpdate class Foo extends Component { shouldComponentUpdate(nextProps,nextState){ if(nextProps.count===this.props.count){ //传入的count与组件当前props的count比较,count没改变,return false,不渲染 return false //不渲染 } return true; //渲染 } render() { console.log("组件渲染"); //可以看到,当父组件的name改变时,子组件不会打印,只有count改变,才会打印,优化性能 return null } } class App extends Component { state = { count: 0, name: 0 } render() { return () } }
//PureComponent
//引入PureComponent import React, { Component, Fragment, PureComponent} from 'react'; //PureComponent,自动比较组件数据是否改变,注意只能比较一层,比如一个对象,对象中的属性改变,他不会重新渲染,只有对象改变,才重新渲染。 class Foo extends PureComponent { render() { console.log("组件渲染"); return null } } class App extends Component { state = { count: 0, name: 0 } render() { return () } }
//hooks Unique optimization method memo
//引入memo import React, { Component, Fragment, memo } from 'react'; //用memo把hooks包裹即可 const Foo = memo(function Foo(props) { console.log("组件渲染"); returncount:{props.count}}) class App extends Component { state = { count: 0, name: 0 } render() { return () } }
recommended Study: "react video tutorial"
The above is the detailed content of How to prevent subcomponents from rendering in react. For more information, please follow other related articles on the PHP Chinese website!