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?