A
A
Andrey Okhotnikov2019-05-14 17:11:10
React
Andrey Okhotnikov, 2019-05-14 17:11:10

The best decision to hang up the output agent on event?

In the official React documentation, the way to hang a function on a click looks like this

import React, { useState } from 'react';

function Example() {
  // Объявляем новую переменную состояния "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Нажми на меня
      </button>
    </div>
  );
}

But the use of arrow functions in rendering is not recommended, because on each render, a new function will be created. Is it correct to use this method or how to solve this situation
import React, { useState } from 'react';

function Example() {
  // Объявляем новую переменную состояния "count"
  const [count, setCount] = useState(0);

  const plus = num => () => setCount(count + num)

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={plus(1)}>
        Нажми на меня
      </button>
    </div>
  );
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-05-14
@tsepen

Everything in the body of the Example function will be executed every render. The only difference of the second method is that it contains additional operations. Moreover, the creation of a handler through a builder, in this case, is an absolutely meaningless operation. Such techniques are appropriate if this builder is reused somewhere and defined outside the component.
If the handler is passed to another React component, then it makes sense to use the useCallback hook. In your case, this makes no sense, since the handler is passed to the native element.

R
Robur, 2019-05-14
@Robur

Who is "not recommended"?
To solve a problem, you need to make sure that there is a problem and clearly formulate it.
If you solve the problem that the code does not fit some recommendations, then this is one thing, but if you solve memory problems during the execution of the application, this is quite another.
In the second case, you should have data obtained from the analysis of how your application works.
The vast majority of render functions are actually called rarely enough for it to matter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question