I am having a ternary operator inside my React prop:
const isItemOne = item.type === 'Item one';
return (
<ChildComponent
myProp={
isItemOne
? generateFunctionOne(itemOne.id, location)
: generateFunctionTwo(itemTwo.url)
}
/>
Does it make sense, in this case to replace the ternary operator with a function and use React useMemo hook here like:
const setValue = useMemo(() => {
if (isItemOne) {
return generateFunctionOne(itemOne.id, location);
}
return generateFunctionTwo(itemTwo.url);
}, [itemOne.id, itemTwo.url]);
2
Answers
Yes, it makes sense to replace the ternary operator with a function and use the React
useMemo
hook in this case.But I think it makes more sense if you add
isItemOne
in dependencies because useMemo will not re-evaluate when theisItemOne
dependency changes.useMemo
is not directly related to usage of ternary operator or not. You use it if you want to cache the result of a (potentially expensive) calculation between re-renders. If your expensive calculation happens to use ternary operator fine, but there is nothing special in ternary operator itself for which you would want to useuseMemo
.