Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs: Best Practice of defining event handlers

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)?

like image 248
Sagnik Chaudhuri Avatar asked Aug 31 '25 04:08

Sagnik Chaudhuri


1 Answers

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.

like image 68
Joseph D. Avatar answered Sep 02 '25 18:09

Joseph D.