Why shouldn't JSX props use arrow functions or bind?

前端 未结 6 1281
孤独总比滥情好
孤独总比滥情好 2020-11-22 13:07

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

6条回答
  •  失恋的感觉
    2020-11-22 13:42

    Why shouldn't JSX props use arrow functions or bind?

    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)

    When is the 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.

    How to solve the ESLint error?

    Classes: Define the handler as method, or class property for this binding.
    Hooks: Use useCallback.

    Middleground

    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
    

提交回复
热议问题