.bind()
or local functions in JSX properties JS-0417109 <input
110 id="remember"
111 type="checkbox"
112 onChange={handleRememberMe}113 value={rememberMe}
114 />
115 <label htmlFor="remember">Remember Me?</label>
68 <h1 className="signin__title">
69 Sign In<span>👋</span>
70 </h1>
71 <form onSubmit={submitHandler}> 72 <div className="form-group">
73 <label htmlFor="username">User Name</label>
74 <input
229 />
230 </div>
231 </div>
232 {form && <Form onClose={handleCloseNewForm} DELETE={deletingID} />}233 </>
234 );
235};
225 onEditCell={(data) => {
226 navigate(`/products/${data.id}/edit`);
227 }}
228 onDelete={handleOpenDeleteForm}229 />
230 </div>
231 </div>
222 <Table
223 cols={cols}
224 data={filteredData}
225 onEditCell={(data) => {226 navigate(`/products/${data.id}/edit`);227 }}228 onDelete={handleOpenDeleteForm}
229 />
230 </div>
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} />
}
}