i want to return two values from usememo hook using react and typescript.
i have code like below,
const renderText = (
text: string,
isAvailable: boolean
) => {
let icon: IconName | undefined = undefined;
let color: StatusColor | undefined = undefined;
if (text === 'N/A') {
icon = 'icon1';
color = 'gray';
} else if (text === 'text-1') {
icon = isAvailable ? 'icon2' : 'icon3';
color = isAvailable ? 'blue' : 'orange';
}
return (
<>
{icon && <Icon name={icon} color={color}/>}
<span>{text}</Text>
</>
);
};
const Component: React.FC<ComponentProps> = ({
text, isAvailable}) => {
return (
<>
{renderText(text,isAvailable)}
</>
);
};
the above code works fine. it returns icon and color based on text and isAvailable values.
now i want to use useMemo hook to return icon and color and use the jsx within the component instead of a seperate function renderText.
so i have tried below,
const Component: React.FC<ComponentProps> = ({
text, isAvailable}) =>{
const { icon, color } = React.useMemo(() => {
let icon: IconName | undefined = undefined;
let color: StatusColor | undefined = undefined;
if (text === 'N/A') {
icon = 'icon1';
color = 'gray';
return {icon, color};
} else if (text === 'text-1') {
icon = isAvailable ? 'icon2' : 'icon3';
color = isAvailable ? 'blue' : 'orange';
return {icon,color};
},
[text]
);
return (
<>
{icon && <Icon name={icon} color={color} />}
<span>{text}</span>
</>
);
};
but the above code doesnt work. it throws error cannot destruction property icon of usememo as its undefined.
i am unsure whats causing this or how to fix this. could someone help me with this. thanks.
2
Answers
In this code, what if
text
has a value of"abc123"
?Then
if (text === 'N/A')
is not run, and alsoelse if (text === 'text-1')
is not run.So the function returns nothing, which is implicitly
undefined
. and now you are tryin to deconstructundefined
which isn’t going to work.You need to ensure that all code path return a value that can be deconstructed.
Maybe something more like this?
Now there are default values that can be changed in certain circumstances, and the function always
return
s an object.I would actually suggest not using
useMemo
and just calculating everything before returning your JSX. These are not intensive calculations so I wouldn’t worry too much about trying to optimize.I’d recommend doing:
Or better yet, move the if/else stuff outside of the component since it can be at the module level with no issues.