stevevar
stevevar

Reputation: 175

React Performance issues in passing callback as props in functional components

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>
    );
}

Upvotes: 1

Views: 1375

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370739

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.

Upvotes: 2

Related Questions