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?
2
Answers
You have at least four choices:
()
necessary to call the function you wrote to replace theuseMemo
call,or
or
el2
,el3
array or an empty oneor
Here’s #1:
Here’s #2 (which is what I’d do):
Here’s #3:
Here’s #4 (only makes sense if you have temporary variables within the block):
Define the function outside of your component. Note that the function now receives
someCondition
as an argument:Now call it inside your component, and pass
someCondition
: