简体   繁体   中英

Rendering React components via object literal

Are there any downsides performance wise, to render react components like these options?

And more specific about option #1:

  • Would it be better to place the icons object outside of the function, maybe even outside of the component?
// option #1
const renderIcon = iconName => {
   const icons = {
       iconX: <IconX />,
       iconY: <IconY />,
       iconZ: <IconZ />,
   };
   return icons[iconName];
};

return <div>{renderIcons('iconX')}</div>


// option #2
const icons = useMemo(() => ({
    iconX: <IconX />,
    iconY: <IconY />,
    iconZ: <IconZ />,
}), [props.iconName]);

return <div>{icons[props.iconsName]}</div>

Speaking of performance, there is a downside since the functions of all components will be executed, including components that are not rendering. Although readability is worse, from a performance perspective it would be better to do a switch or ternary rendering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM