I\'m running lint with my React app, and I receive this error:
error JSX props should not use arrow functions react/jsx-no-bind
A
Mostly, because inline functions can break memoization of optimized components:
Traditionally, performance concerns around inline functions in React have been related to how passing new callbacks on each render breaks
shouldComponentUpdate
optimizations in child components. (docs)
It is less about additional function creation cost:
Performance issues with
Function.prototype.bind
got fixed here and arrow functions are either a native thing or are transpiled by babel to plain functions; in both cases we can assume it’s not slow. (React Training)I believe people claiming function creation is expensive have always been misinformed (React team never said this). (Tweet)
react/jsx-no-bind
rule useful?You want to ensure, that memoized components work as intended:
React.memo
(for function components)PureComponent
or custom shouldComponentUpdate
(for class components)By obeying to this rule, stable function object references are passed. So above components can optimize performance by preventing re-renders, when previous props have not changed.
Classes: Define the handler as method, or class property for this
binding.
Hooks: Use useCallback.
In many cases, inline functions are very convenient to use and absolutely fine in terms of performance requirements. Unfortunately, this rule cannot be limited to only memoized component types. If you still want to use it across-the-board, you could e.g. disable it for simple DOM nodes:
rules: {
"react/jsx-no-bind": [ "error", { ignoreDOMComponents: true } ],
}
const Comp = () => console.log("Hello!")} />; // no warning