.bind()
or local functions in JSX properties JS-0417Using .bind()
or passing local callback functions as props to react component incurs a performance overhead.
Consider using React.useCallback
, or if possible, moving the callback definition outside the component.
EXCEPTIONS: This rule may not apply if your react component is only rendered once, or if your application is not performance sensitive. In such cases, consider adding a skipcq to prevent DeepSource from raising this issue on a single component. Alternatively, for small applications, you could add this issue in the ignore rules section.
Note that the performance overhead is not determined by the size of the callback function, but instead the number of times the component is rendered.
If the callback passed to a prop is local to the render function, it will get recreated every time the component renders.
This affects performance by causing unnecessary re-renders if a brand new function is passed as a property to a component that uses a reference equality check on the property to determine if it should update.
Using the useCallback
hook on functional components, or a method on class components is more performant.
function CardWrapper() {
// the function `handleClick` is recreated every time
// a `CardWrapper` component is rendered.
const handleClick = (e) => displayCardDetails(e)
return <Card onClick={handleClick} />
}
function CardWrapper_() {
return <Card onClick={(e) => displayCardDetails(e)} />
}
class _CardWrapper extends React.Component {
render() {
return <Card onClick={(e) => displayCardDetails(e)} />
}
}
function CardWrapper() {
// `handleClick` is no longer recreated on every render.
const handleClick = React.useCallback((e) => displayCardDetails(e))
return <Card onClick={handleClick} />
}
class CardWrapper_ extends React.Component {
handleClick(e) {
displayCardDetails(e)
}
render() {
return <Card onClick={this.handleClick} />
}
}