DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Badri
Badri

Posted on

React - Combining useMemo and Switch

useMemo is a react hook that gets executed only if any of the dependency changes. We can make it work like a switch by returning an object whose key will be the switch expression.

const Form = () => {
    switch(selectedUser){
        case "Admin" : return AdminForm;
                       break;
        case "User" : return UserForm;
                      break;
    }
}
//*AdminForm and UserForm are functional components

//This code is equivalent to 
const Form = useMemo(()=>{
   return { 
      "Admin" : AdminForm,
      "User" : UserForm,
   }[selectedUser];
},[selectedUser]);

/*
Breaking this down, if selectedUser is "Admin", we would return 
   { 
     "Admin" : AdminForm,
     "User" : UserForm,
   }["Admin"];
which is AdminForm.
*/
Enter fullscreen mode Exit fullscreen mode

Here, Form gets executed only when selectedUser changes, so the expression need not be evaluated every time. This method allows us to optimise the expression evaluation as switch needs to execute it every time but useMemo doesn't.

Top comments (2)

Collapse
mattcale profile image
Matthew Cale

Super simple and explains a great deal. Thanks!

Collapse
kbadri01 profile image
Badri Author

Thank You!

🌚 Life is too short to browse without dark mode