0

I'm using a functional component of react, and I'd like to ask how to efficiently deliver functions to events.

See this article at https://reactjs.org/docs/faq-functions.html

According to the official documentation, "Using an arrow function in render creates a new function etch time the component renders, which may break optimizations based on Strictity composite."

If there is no argument passed to the function, I understand that the check1 code is not a good code, is that right?

const Foo = () => {
  const example = () => console.log("hi");

  return {
    <div onClick={() => example()}>click1</div>
    <div onClick={example()}>click2</div>
  }
}

Is there a difference in performance between click1 and click2?

Hyeongrok
  • 31
  • 1
  • 5
  • See the answers to the linked question. But just a side note: Since `example` doesn't pay any attention to any arguments it's passed, you can save a function allocation by doing `onClick={example}` instead of `onClick={() => example()}`. That means `example` will get passed the event object for the event, but since `example` doesn't pay any attention to it, to makes no real difference. – T.J. Crowder Sep 04 '22 at 07:43
  • \* *it* makes no difference (doh!) – T.J. Crowder Sep 04 '22 at 07:51

2 Answers2

1

It's not about the arrow functions only, declare any function in the component scope whenever the component rerenders it will re-initialize, to stop that from happening, you need to save the function referance, and that's happen when you use useCallback hook to wrap your function.

const example = useCallback(() => console.log("hi"), []);

And you can add the function dependencies to the array which second parameters to the useCallback hook, and whenever any of the dependencies change, the function will reinitialize to get the newest value of the dependencies.

For more resources.

Mina
  • 14,386
  • 3
  • 13
  • 26
0

Normally you don't need to memoize a function, it will re-render every time and it's fine. Memoizing functions requires a memory cost, it's not free. A common situation where you need useCallback is when you pass your function as a dependency to useEffect.

const fn = () => {}

useEffect(() => {
  fn();
}, [fn])
 

In this situation you don't want to call useEffect on every render, so you should wrap fn in useCallback. And it will be the same on every render

Read more or any article on "why I shouldn't use useCallback"

Dmitriy Zhiganov
  • 1,060
  • 1
  • 5
  • 14