Is it a good idea to memoize all of my react components?

后端 未结 2 2015
自闭症患者
自闭症患者 2021-01-13 14:13

I\'ve recently decided to refresh on react\'s documentation and came across https://reactjs.org/docs/react-api.html#reactmemo (React.memo).

At first glance it looked

2条回答
  •  感动是毒
    2021-01-13 15:02

    For shorter explanation:

    If React.memo() everything makes React more efficient and optimized, it should be considered as a default behavior, not only an option (like pure function).

    Basically, React.memo() prevents redundant rerenders by comparing the component's previous and current props.

    
      
    
    

    Normally, when the Parrent rerenders, the Child rerender as well by default.

    With React.memo(), if the props passed into Child are not changed when Parent rerender, Child does not rerender.

    The question here is: why React knows props passed to Child was not changed in the current rerender ?

    The answer is: React itself has to do a comparison, and it is the cost of React.memo()

    If the time to comparison > the time to just rerender the whole Child component, it even slows down your app.

提交回复
热议问题