.bind()
or local functions in JSX properties JS-0417423 <Select
424 options={memoryOptions}
425 defaultValue={memoryOptions[1]}
426 onChange={(e) => setFlagMemory(e?.value ?? 256)}427 />
428 </div>
429 <hr />
412 className="form-control"
413 type="number"
414 value={flagTimeout}
415 onChange={(e) => setFlagTimeout(Number(e.target.value))}416 disabled={!useFlagTimeout}
417 />
418 <span className="input-group-text">s</span>
403 <div className="input-group">
404 <Button
405 kind={useFlagTimeout ? "success" : "danger"}
406 onClick={() => setUseFlagTimeout((v) => !v)}407 tooltip={"Use timeout"}
408 >
409 <FontAwesomeIcon icon={faListCheck} />
134 return (
135 <>
136 <div className="d-flex flex-column align-items-center w-100">
137 <Button kind="primary" onClick={refreshData} disabled={refreshDisabled}>138 Refresh runs
139 </Button>
140 <table className="table table-striped table-hover">
391 </span>
392 <Button
393 kind={"primary"}
394 onClick={() => setFlagProcessors((v) => v + 1)}395 style={{ height: 44 }}
396 tooltip="Increase processor count for each solver"
397 >
Using .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} />
}
}