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.
*/
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)
Super simple and explains a great deal. Thanks!
Thank You!