Home > Software design >  React Js best practice - onClick event
React Js best practice - onClick event

Time:01-15

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

CodePudding user response:

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.

CodePudding user response:

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

  •  Tags:  
  • Related