score:3

Accepted answer

wrap 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]);

score:0

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]);

Related Query

More Query from same tag