I have a simple function that has return values based on if statements. I need to useMemo on this function that keep the same values between renders. How can I do this?
const getStatusState = () => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
};
How does useMemo work on this function as I am not using useState I am getting the value a from props.
I have a simple function that has return values based on if statements. I need to useMemo on this function that keep the same values between renders. How can I do this?
const getStatusState = () => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
};
How does useMemo work on this function as I am not using useState I am getting the value a from props.
Share Improve this question asked Nov 3, 2020 at 1:58 user14539016user145390162 Answers
Reset to default 4Wrap it with React.useMemo
and pass a
into the dependency array so it fires only if a
changes.
const getStatusState = React.useMemo(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);
The above answer is valid only if you want to use getStatusState
as a constant. If you use getStatusState
as a function it will give Uncaught TypeError:
. ie: if you log below using the console
const getStatusState = React.useMemo(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);
Logs will be:
console.log(getStatusState); => 'STRING_A' or 'STRING_B' or 'N/A'
console.log(getStatusState()); => Uncaught TypeError: getStatusState is not a function
To solve the above problem and use getStatusState
as function ie: getStatusState()
, there are two ways in React:
1 Using useMemo() and return a Function
const getStatusState = React.useMemo(
() => () => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
},
[a]
);
2 Using useCallback()
const getStatusState = React.useCallback(() => {
if (a === 'STRING_A') {
return 'duplicate';
}
if (a === 'STRING_B') {
return 'good';
}
return 'N/A';
}, [a]);