I want to achieve similar result to this code:
const myResult = useMemo(
() => {
var arr = ["el1"]
if(someCondition){
arr.push( "el2", "el3")
}
return arr
}, [someCondition]
)
but without using useMemo(), just simple const (it is simple so can be recomputed with every render and I want to maintain a code as simple as it’s possible)
I was thinking about something like this
const myResult = () => {
var arr = ["el1"]
if(someCondition){
arr.push( "el2", "el3")
}
return arr
}
but in that case array is a function returning array of strings, not array of strings it self.
I know I can do it like this
const myResult = someCondition ? ["el1", "el2", "el3"] : ["el1"]
but I don’t like here that "el1" is duplicated in code…
Is it possible to achieve my goal or I overthink the problem?
>Solution :
You have at least four choices:
- Add the
()necessary to call the function you wrote to replace theuseMemocall,
or - Don’t use a function wrapper at all (this is what I’d do)
or - As deceze suggested for this specific case, use spread notation to spread out either your
el2,el3array or an empty one
or - If your real use case requires temporary variables, etc., use an anonymous/standalone block rather than a function.
Here’s #1:
const myResult = (() => {
const arr = ["el1"];
if (someCondition) {
arr.push( "el2", "el3");
}
return arr;
})();
Here’s #2 (which is what I’d do):
const myResult = ["el1"];
if (someCondition) {
myResult.push( "el2", "el3");
}
Here’s #3:
const myResult = ["el1", ...(someCondition ? ["el2", "el3"] : [])];
Here’s #4 (only makes sense if you have temporary variables within the block):
const myResult = ["el1"];
{
if (someCondition) {
myResult.push( "el2", "el3");
}
}