Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks and jsx-no-lambda warning

so now that we cant use the hooks as old style of event functions beside disabling the warning what is the best way to call event function that does not violate the rule

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}> // Lambdas are forbidden in JSX attributes due to their rendering performance impact (jsx-no-lambda)
        Click me
      </button>
    </div>
  );
}
like image 755
Amir-Mousavi Avatar asked Mar 04 '19 12:03

Amir-Mousavi


1 Answers

With hooks the performance penalty to creating inline arrow function is negligible to the benefits that it has over class components and hence you need not worry arrow functions in render.

You can disable this eslint rule.

However you still improve your code by writing a increment method and memoizing it using useCallback hook. This is particularly useful whenn you are trying to pass down the handler to nested components which you can then optimize for re-render by using React.memo

const Button = React.memo(function Btn({increment}) {
    return (
       <button onClick={increment}>
          Click me
      </button>
    )
})
function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);
  const increment = React.useCallback(() => {
      setCount(prev => prev+1);
  }, [])
  return (
    <div>
      <p>You clicked {count} times</p>
      <Button increment={increment}/>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>
like image 149
Shubham Khatri Avatar answered Oct 17 '22 16:10

Shubham Khatri