skip to Main Content

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


  1. You have at least four choices:

    1. Add the () necessary to call the function you wrote to replace the useMemo call,

      or
    2. Don’t use a function wrapper at all (this is what I’d do)

      or
    3. As deceze suggested for this specific case, use spread notation to spread out either your el2, el3 array or an empty one

      or
    4. 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");
        }
    }
    
    Login or Signup to reply.
  2. Define the function outside of your component. Note that the function now receives someCondition as an argument:

    const getMyResult = (someCondition) => {
      const arr = ["el1"]
      if (someCondition) arr.push("el2", "el3")
      return arr
    }
    

    Now call it inside your component, and pass someCondition:

    const Comp = ({ someCondition }) => {
      const myResult = getMyResult(someCondition)
      //...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search