I saw many article said that define inline function in render function in react can cause to performance issue.
Therefore they recommend to define the function outside of the render function and use it where i need (onClick etc).
I built a sample code that i have a list of button and each button will increase the state by the index in the list, But its throw error.
How i can pass parameter and not use inline function in onClick
const App = () => {
const [number, setNumber] = useState(1);
const increaseNumber = (num) => {
setNumber((prevState) => prevState + num);
};
return (
<div>
{[...Array(5)].map((item, index) => (
<button key={index} onClick={increaseNumber(index)}>
{`increase by ${index}`}
</button>
))}
<div>{number}</div>
</div>
);
};
export default App;
onClick" You can't. Because the function depends on the.mapcallback variable and is therefore different for every element of the array, the function has to be created (directly or indirectly) in the.mapcallback.useCallbackto define it only on mount. EDIT: for this function is microptimization, but if you looping to an array with 1000 entities it could cost some time