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>
);
}
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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With