-1

I worked with 3 different scenarios to call a function using onClick event, but I was never sure about which one I should stick with, I will demonstrate my question with a basic example but let's imagine our tFunction is more complicated than updating a state.

const [state, setState] = useState("");

1st scenario :

const tFunction = (e) => {
const tValue = e.target.getAttribute("name");
setState(tValue)};

<button name={"some data"} onClick={tFunction}>Press me</button>

2nd scenario :

  const tFunction = (value) => {setState(value)};

  <button onClick={() => tFunction("some data")}> Press me </button>

3rd scenario :

  <button onClick={() => setState("some data")}> Press me </button>

My question is : what is the best scenario that I should always follow?

demo

MertHaddad
  • 447
  • 1
  • 7
  • 15
  • 1
    What is `value` in your 2nd and 3rd scenarios? it is not defined – Ba2sik Jan 14 '22 at 19:42
  • Related for non-hooks: [Binding vs Arrow-function (in JavaScript, or for react onClick)](https://stackoverflow.com/questions/50375440/binding-vs-arrow-function-in-javascript-or-for-react-onclick). That said, the code snippets here aren't clearly similar as Ba2sik mentioned, nor are they valid JS. Please share runnable, working snippets. – ggorlen Jan 14 '22 at 19:43
  • I replace value with just a text something to update the state with. I provided a demo. – MertHaddad Jan 14 '22 at 19:57

2 Answers2

1

Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.

(From React documentation: https://reactjs.org/docs/faq-functions.html)

Thus, you should go 1st scenario.

-1

The first scenario makes you code run faster and can be reusable for other buttons, so I suggest the first scenario

Icekid
  • 435
  • 3
  • 14