React.memo 및 React.PureComponent

5502 단어 reactwebdev

개요


  • React.PureComponent
  • React.memo
  • References

  • 리액트.퓨어컴포넌트

    In react, components can be defined as functions or ES6 classes. All class components are sub classes of either Component or PureComponent . To understand when PureComponent base class is used for declaring your class component, it is important to understand when a react component defined as a sub class of Component re-renders.

    When a class component is a sub class of Component , it is re-rendered whenever:

    • state changes
    • context changes
    • parent re-renders
    • props change
    You can see from the above that a component is re-rendered whenever its parent re-renders though its context, state or props haven't changed. To prevent a component from re-rendering because of its parent's re-render, you can declare it as a sub class of PureComponent . PureComponent implements shouldComponentUpdate out of the box. It does a shallow comparison of props and state . If the state and props haven't changed, react doesn't re-render the component even if the parent re-renders. Since this is a shallow comparison, pureComponent should be avoided if your component is deeply nested because react can produce false-negatives for deeper differences. It should only be used if the component is pure.
    According to
    react documentation :

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



    다음은 ES6 클래스를 사용하여 PureComponent를 정의하는 방법입니다.

    class App extends React.PureComponent{
        constructor(props){
           super(props);
           this.state = { };
       }
       render(){
        return <div className = "app"> Hello World! </div>
       }
    }
    


    리액트.메모

    React.memo is the functional component equivalent of React.PureComponent . It is a higher-order component. If React.memo wraps a component, it memoizes the rendered output and skips subsequent renders if state, props, or context have not changed. It is worth pointing out that React.memo checks for props changes. If the component's state or context change, the component is re-rendered even if the props haven't. React.memo makes a shallow comparison of props . It also takes a function as second argument if you want to have control over the comparison.

    React.memo(App, function comparator(prevProps, nextProps){
    });
    

    The second argument, comparator , returns true if its arguments are equal and false otherwise. This helps React.memo determine whether to re-render the component or not.


    Thanks for reading this article till the end. If you find it useful, consider sharing it on or any other platform. Others might find it useful too and if you notice something which is technically inaccurate, please leave a comment below.

    참고문헌


  • React documentation
  • 좋은 웹페이지 즐겨찾기