React Performance issues in passing callback as props in functional components

和自甴很熟 提交于 2021-02-10 14:36:41

问题


React doc

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }
}

React doc :-

The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.

This is fine for class based component, what about functional component.

Can we use like below and experience performance issues like it stated because different callback is created each renders? It says it works most of the cases, so I am not sure if we should leave it as it is or use React hook useCallBack for all functional components with callbacks.

I have got 3 diff types

const LoggingButtion = (props)=>{
 const [ loggedStatus, setLogStatus] = useState(false);

const handleClick =()=> {
    console.log('Button Clicked');
   setLogStatus(true)
  }
 return (
      <button onClick={() => { console.log('button clicked'); setLogStatus(false)} > // Type1
      <button onClick={() => handleClick()}> // type 2
      <button onClick={handleClick}> // type 3
        Click me
      </button>
    );
}

回答1:


Can we use like below and experience performance issues like it stated because different callback is created each renders? It says it works most of the cases, so I am not sure if we should leave it as it is or use React hook useCallBack for all functional components with callbacks.

It only matters if the app is large enough that it's causing performance issues, which isn't likely. Avoiding useCallback makes the code easier to read and will work just fine in 97% of cases. But if you do find a situation where child components are re-rendering too often, and you have enough of those components that the performance impact is visible, go ahead and use useCallback:

const handleClick = useCallback(() => () => {
  console.log('Button Clicked');
  setLogStatus(true)
}, []);

But, note that you don't have child components here, only <button>s. While a different event listener has to be attached to each element each render, that's not likely to be a problem either.

Feel free to do what you're currently doing, without useCallback, and only change to useCallback if re-rendering proves to be a problem.



来源:https://stackoverflow.com/questions/64547776/react-performance-issues-in-passing-callback-as-props-in-functional-components

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!