I recently started using ReactJs and I want to know what is the best practice of defining event handlers in React. This is how I've been using react event handlers:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [counter, setCounter] = useState(0);
const handleButtonClick = () => {
setCounter(counter + 1);
};
return (
<div className="App">
<button onClick={() => handleButtonClick()}>
Click Me To increase counter
</button>
<div>
<h4>Counter value is: </h4>
{counter}
</div>
</div>
);
}
I have also heard arguments against this logic. Some say it is better to define event handlers outside the definition of the component (App
in our case). This way, it becomes clear, clean and concise, instead of creating a mess of multiple functions (event handlers or not) inside the component. For example:
import React, { useState } from "react";
import "./styles.css";
const handleButtonClick = (setCounter, counter) => () => {
setCounter(counter+1);
};
export default function App() {
const [counter, setCounter] = useState(0);
return (
<div className="App">
<button onClick={handleButtonClick(setCounter, counter)}>
Click Me To increase counter
</button>
<div>
<h4>Counter value is: </h4>
{counter}
</div>
</div>
);
}
CodeSandbox Link for second approach
I want to know which is the best practice of defining functions? Should event handlers be also defined globally above the function component(App Component in this case
)?
Should event handlers be also defined globally above the function component?
NO.
Defining event handlers, outside the component, that modifies a component's state breaks cohesion.
An event handler, within a component, explains the different interactions of the component. Having a "wrapper" handler simply breaks the single level of abstraction.
My two cents.
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