skip to Main Content

I am having a ternary operator inside my React prop:

        const isItemOne = item.type === 'Item one';

        return (
          <ChildComponent
            myProp={
              isItemOne
                ? generateFunctionOne(itemOne.id, location)
                : generateFunctionTwo(itemTwo.url)
            }
          />

Does it make sense, in this case to replace the ternary operator with a function and use React useMemo hook here like:

       const setValue = useMemo(() => {
          if (isItemOne) {
            return generateFunctionOne(itemOne.id, location);
          }
          return generateFunctionTwo(itemTwo.url);
        }, [itemOne.id, itemTwo.url]);

2

Answers


  1. Yes, it makes sense to replace the ternary operator with a function and use the React useMemo hook in this case.

    But I think it makes more sense if you add isItemOne in dependencies because useMemo will not re-evaluate when the isItemOne dependency changes.

    const setValue = useMemo(() => {
      if (isItemOne) {
        return generateFunctionOne(itemOne.id, location);
      }
      return generateFunctionTwo(itemTwo.url);
    }, [isItemOne, itemOne.id, itemTwo.url]);
    
    Login or Signup to reply.
  2. Does it make sense, in this case to replace the ternary operator with
    a function and use React useMemo hook here like:

    useMemo is not directly related to usage of ternary operator or not. You use it if you want to cache the result of a (potentially expensive) calculation between re-renders. If your expensive calculation happens to use ternary operator fine, but there is nothing special in ternary operator itself for which you would want to use useMemo.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search