Consider i got such example:
import React, { useMemo, useCallback } from 'react'
const Hello = (props) => {
const { firstName, lastName } = props
const fullName = useMemo(() => `${firstName} ${lastName}`, [firstName, lastName])
const sayHello = useCallback(() => {
console.log(`Hello, ${fullName}`)
}, [fullName])
return (
// ...
)
}
export default Hello
Basically i have a component called Hello, and it receives two props firstName and lastName, then i need to calculate fullName based on those two props and has a function sayHello() uses fullName to do something
So my question is: In here is it necessary to use useMemo() and useCallback() for performance optimization? It seems like its kind of overuse of useMemo() and useCallback() for just a little benefit, and i am not sure if this might cause potential side effects?
In that example, different answers for that use of
useMemoand that use ofuseCallback:The
useMemois almost certainly overkill; it's just not that expensive forsayHelloto build that string (vs. creating a new function to pass touseMemoon every render).The answer for
useCallbackdepends on howsayHellois used. IfsayHellois supplied as a prop to a component that is memoized on that prop (like aPureComponent, something that implementsshouldComponentUpdatedirectly, or the result of wrapping a component withReact.memo), it can be a performance optimization to keepsayHellostable by memoizing it as you've shown so that the component(s) you're passing it to don't have to re-render when it changes. If not, though, it's probably not useful, no.I agree with Drew Reese: Start simple by just writing your functions, and then apply optimization to code you see performing poorly. (Although there are some situations where you might be proactive based on previous experience — say, passing a callback you could memoize to a couple of hundred pure child components...)