0

I'm always confused when define function in React functional component without any dependencies.

For example,

const HelloWorld = () => {
  const getHelloWorldText = useCallback(() => {
    return "HelloWorld"
  }, [])

  return <>{getHelloWorldText()}</>
}

It's a simplified component, just imagine HelloWorld is updated every 5 seconds. useCallback is needed for optimization preventing redefine.

However, it's possible like below.

const getHelloWorldText = () => {
  return "HelloWorld"
}

const HelloWorld = () => {
  return <>{getHelloWorldText()}</>
}

If there's no dependency, above example is more costless than useCallback example, but it's not a pure function.

Which do you prefer? And why?

Benjamin
  • 707
  • 3
  • 8
  • 28
  • 1
    Does this answer your question? https://stackoverflow.com/questions/55310682/should-i-wrap-every-prop-with-usecallback-or-usememo-when-to-use-this-hooks – rfestag Jul 17 '20 at 02:53

1 Answers1

1

Prematurely using useCallback to optimise can often lead to worse performance. It is recommended to only start using it when you have a measurable performance issue, so you can test whether the overhead of useCallback is worth the memoization it brings.

Also, in your example code, because the dependency array at the end is empty, it will always return the same value, as useCallback works by only re-running the given function when a variable in that array has changed.


This is what I would do:

const HelloWorld = () => {
  const getHelloWorldText = () => {
    return "HelloWorld"
  }

  return <>{getHelloWorldText()}</>
}
Luke Storry
  • 6,032
  • 1
  • 9
  • 22