react#memo JavaScript Examples
The following examples show how to use
react#memo.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js From viade_es2a with BSD 2-Clause "Simplified" License | 6 votes |
AutoSaveSpinner = memo(({ inProgress, result, setResult, setSavingProcess }) => {
const [timer, setTimer] = useState(null);
useEffect(
() => () => {
clearTimeout(timer);
},
[]
);
useEffect(() => {
if (result) {
if (timer) clearTimeout(timer);
if (result.toLowerCase() === 'success') {
setTimer(
setTimeout(() => {
setResult(null);
setSavingProcess(false);
}, 2000)
);
}
}
}, [result]);
return (
<AutoSaveSpinnerWrapper>
{inProgress && (
<div>
<FontAwesomeIcon icon="spinner" spin />
</div>
)}
{result && !inProgress && (
<div>
{result.toLowerCase() === 'success' && <FontAwesomeIcon icon="check-circle" />}
{result.toLowerCase() === 'error' && <FontAwesomeIcon icon="exclamation-triangle" />}
</div>
)}
</AutoSaveSpinnerWrapper>
);
})
Example #2
Source File: Feature.js From Website with MIT License | 6 votes |
Feature = memo(props => {
const innerBody = [
<>
<h1>{props.title}</h1>
{props.subtitle && <h2>{props.subtitle}</h2>}
<p>{props.body}</p>
</>,
<>
{props.images.map((image, idx) => (
<LazyLoad debounce={false} offsetVertical={700} offsetTop={700}>
<img key={image} src={image} alt="" className={props.imageClassNames?.[idx]} />
</LazyLoad>
))}
</>,
];
return (
<section className="feature">
<div className={`left ${props.images.length === 2 ? "two-images" : ""}`}>
{innerBody[props.reversed ? 1 : 0]}
</div>
<div className={`right ${props.images.length === 2 ? "two-images" : ""}`}>
{innerBody[!props.reversed ? 1 : 0]}
</div>
</section>
);
})
Example #3
Source File: Modals.js From filen-mobile with GNU Affero General Public License v3.0 | 6 votes |
FullscreenLoadingModal = memo(() => {
const fullscreenLoadingModalVisible = useStore(useCallback(state => state.fullscreenLoadingModalVisible))
const setFullscreenLoadingModalVisible = useStore(useCallback(state => state.setFullscreenLoadingModalVisible))
const setFullscreenLoadingModalDismissable = useStore(useCallback(state => state.setFullscreenLoadingModalDismissable))
const fullscreenLoadingModalDismissable = useStore(useCallback(state => state.fullscreenLoadingModalDismissable))
if(!fullscreenLoadingModalVisible){
return null
}
return (
<Pressable style={{
position: "absolute",
height: "100%",
width: "100%",
backgroundColor: "rgba(0, 0, 0, 0.4)",
justifyContent: "center",
alignItems: "center"
}} onPress={() => {
if(fullscreenLoadingModalDismissable){
setFullscreenLoadingModalVisible(false)
setFullscreenLoadingModalDismissable(false)
}
}}>
<ActivityIndicator size={"small"} color="white" />
</Pressable>
)
})
Example #4
Source File: footer-feedback.js From Nextjs-ja-translation-docs with MIT License | 6 votes |
Emoji = memo(({ hex, alt = 'emoji' }) => (
<img
decoding="async"
width={['1f600', '1f62d', '1f615'].includes(hex) ? 24.5 : 22}
height={['1f600', '1f62d', '1f615'].includes(hex) ? 24.5 : 22}
src={`https://assets.vercel.com/twemoji/${hex}.svg`}
alt={alt}
loading="lazy"
style={{
transform: ['1f600', '1f615'].includes(hex) ? 'translateY(0.5px)' : 'none'
}}
/>
))
Example #5
Source File: index.js From prisma.pan.dev with MIT License | 6 votes |
DocSidebarItems = memo(({ items, ...props }) => (
<>
{items.map((item, index) => (
<DocSidebarItem
key={index} // sidebar is static, the index does not change
item={item}
{...props}
/>
))}
</>
))
Example #6
Source File: Modal.js From instaclone with Apache License 2.0 | 6 votes |
Modal = memo(({ component, hideModal, ...additionalProps }) => {
const modalRoot = document.querySelector('#modal-root');
const el = document.createElement('div');
const Child = require(`../../components/${component}`).default;
el.className = 'modal grid';
useEffect(() => {
const hide = ({ target }) => {
if (target === el || !el.contains(target)) {
hideModal(component);
}
};
el.addEventListener('mousedown', hide, false);
modalRoot.appendChild(el);
return () => {
el.removeEventListener('mousedown', hide, false);
modalRoot.removeChild(el);
};
}, [el, modalRoot, hideModal, component]);
return ReactDOM.createPortal(
<Child hide={() => hideModal(component)} {...additionalProps} />,
el
);
})
Example #7
Source File: ResourceCards.js From webDevsCom with MIT License | 6 votes |
ResourceCards = memo(() => {
const ResourceContext = useContext(resourceContext);
const { category, searchText, resources } = ResourceContext;
return (
<div
className='columns is-multiline is-centered fadeInUp'
style={{ margin: 'auto', animationDelay: '0.85s' }}
>
{
resources.length === 0 &&
window.location.pathname === '/resources' ? (
<NoData text={`There is no resources present for searched Keyword ${searchText}.
Please try searching for something else.`} />
) : (
resources.length === 0 &&
window.location.pathname === '/bookmarked') ? (
<NoData
text={
searchText === '' && category === 'all'
? 'You have not Bookmarked any Resources.'
: category !== 'all'
? `You have not Bookmarked any Resources of category "${category}".`
: `You have not Bookmarked any resources with search keyword "${searchText}"`
}
/>
) : (
resources.map((resource) => (
<ResourceCard key={resource.id} resource={resource} />
))
)}
</div>
);
})
Example #8
Source File: Jobs.js From ui-data-export with Apache License 2.0 | 6 votes |
Jobs = memo(() => (
<div
data-test-jobs-container
className={css.jobsContainer}
>
<AccordionSet>
<RunningJobs />
</AccordionSet>
</div>
))
Example #9
Source File: ImageView.js From label-studio-frontend with Apache License 2.0 | 6 votes |
RegionsLayer = memo(({ regions, name, useLayers, showSelected = false }) => {
const content = regions.map((el) => (
<Region key={`region-${el.id}`} region={el} showSelected={showSelected} />
));
return useLayers === false ? (
content
) : (
<Layer name={name}>
{content}
</Layer>
);
})
Example #10
Source File: ItemLibrary.jsx From airboardgame with MIT License | 6 votes |
NewItem = memo(({ type, template, component: Component, name }) => {
const { pushItem } = useItemActions();
const addItem = React.useCallback(async () => {
pushItem({
...(typeof template === "function" ? template() : template),
id: uid(),
type,
});
}, [pushItem, template, type]);
return (
<StyledItem onClick={addItem}>
<div className="item-library__component">
<Component
{...(typeof template === "function" ? template() : template)}
width={size}
height={size}
size={size}
/>
<span>{name}</span>
</div>
</StyledItem>
);
})
Example #11
Source File: Filter.jsx From youtube-clone-spa with MIT License | 6 votes |
RemoveSvg = memo(({ WhoActive, text }) => {
// Theme
const Theme = useSelector((state) => state.Theme.isDarkTheme);
return WhoActive === text ? (
<div className={styles.filter__icon}>
<XSvg Theme={Theme} />
</div>
) : (
<div></div>
);
})
Example #12
Source File: OfflineData.js From youdidao-unmanned-shop with MIT License | 6 votes |
OfflineData = memo(
({ activeKey, loading, offlineData, offlineChartData, handleTabChange }) => (
<Card
loading={loading}
className={styles.offlineCard}
bordered={false}
style={{ marginTop: 32 }}
>
<Tabs activeKey={activeKey} onChange={handleTabChange}>
{offlineData.map(shop => (
<TabPane tab={<CustomTab data={shop} currentTabKey={activeKey} />} key={shop.name}>
<div style={{ padding: '0 24px' }}>
<TimelineChart
height={400}
data={offlineChartData}
titleMap={{
y1: formatMessage({ id: 'app.analysis.traffic' }),
y2: formatMessage({ id: 'app.analysis.payments' }),
}}
/>
</div>
</TabPane>
))}
</Tabs>
</Card>
)
)
Example #13
Source File: index.js From ant-simple-pro with MIT License | 6 votes |
Buttons = memo(function Buttons({ fontSize, title, iconClass, fill, ...props }) {
return (
<>
<Button {...props}>
{iconClass ? <SvgIcon iconClass={iconClass} fill={fill} fontSize={fontSize} /> : null}
<span>{title}</span>
</Button>
</>
)
})
Example #14
Source File: Footer.js From lx-music-mobile with Apache License 2.0 | 6 votes |
Loading = memo(() => {
const theme = useGetter('common', 'theme')
const { t } = useTranslation()
return (
<View style={{ alignItems: 'center', padding: 10 }}>
<Text style={{ color: theme.normal30 }}>{t('list_loading')}</Text>
</View>
)
})
Example #15
Source File: PluginCard.js From Website with MIT License | 5 votes |
PluginCard = memo(({ guild: guildId, id, active, ...props }) => {
const { setActivePlugins, setDashboardOpen } = useContext(DiscordContext);
const [enabled, setEnabled] = useState(true);
useEffect(() => {
setEnabled(!!active);
}, [active]);
const handleChange = e => {
const checked = e.target.checked;
setEnabled(checked);
setActivePlugins(prev => {
const newPlugs = { ...prev, [id]: checked };
firebase.db
.collection("DiscordSettings")
.doc(guildId || " ")
.update({
activePlugins: newPlugs,
})
.then(() => setDashboardOpen(true))
.catch(err => {
firebase.db
.collection("DiscordSettings")
.doc(guildId || " ")
.set({
activePlugins: newPlugs,
});
});
return newPlugs;
});
};
return (
<div className={`plugin-card ${props.comingSoon ? "coming-soon" : ""}`}>
<span className="plugin-switch">
<BlueSwitch checked={enabled} onChange={handleChange} color="primary" name={id} inputProps={{ "aria-label": "primary checkbox" }} />
</span>
<A className="plugin-card-a" href={active ? `${props.match.url}/${id}` : "#"} local>
<div className="image">
<img src={`${process.env.PUBLIC_URL}/${props.image}`} alt="" />
</div>
<div className="text">
<h2>{props.title}</h2>
<h4>{props.description}</h4>
</div>
</A>
</div>
);
})
Example #16
Source File: Dialogs.js From filen-mobile with GNU Affero General Public License v3.0 | 5 votes |
ConfirmPermanentDeleteDialog = memo(({ navigation }) => {
const [darkMode, setDarkMode] = useMMKVBoolean("darkMode", storage)
const confirmPermanentDeleteDialogVisible = useStore(useCallback(state => state.confirmPermanentDeleteDialogVisible))
const setConfirmPermanentDeleteDialogVisible = useStore(useCallback(state => state.setConfirmPermanentDeleteDialogVisible))
const [buttonsDisabled, setButtonsDisabled] = useState(false)
const [lang, setLang] = useMMKVString("lang", storage)
const currentActionSheetItem = useStore(useCallback(state => state.currentActionSheetItem))
useEffect(() => {
setButtonsDisabled(false)
}, [confirmPermanentDeleteDialogVisible])
return (
<>
{
typeof currentActionSheetItem !== "undefined" && (
<Dialog.Container
visible={confirmPermanentDeleteDialogVisible}
useNativeDriver={false}
onRequestClose={() => setConfirmPermanentDeleteDialogVisible(false)}
onBackdropPress={() => setConfirmPermanentDeleteDialogVisible(false)}
>
<Dialog.Title>{i18n(lang, "itemDeletedPermanentlyConfirmation", true, ["__NAME__"], [currentActionSheetItem.name])}</Dialog.Title>
<Dialog.Button label={i18n(lang, "cancel")} disabled={buttonsDisabled} onPress={() => setConfirmPermanentDeleteDialogVisible(false)} />
<Dialog.Button label={i18n(lang, "deletePermanently")} disabled={buttonsDisabled} onPress={() => {
setButtonsDisabled(true)
setConfirmPermanentDeleteDialogVisible(false)
useStore.setState({ fullscreenLoadingModalVisible: true })
deleteItemPermanently({ item: currentActionSheetItem }).then(async () => {
DeviceEventEmitter.emit("event", {
type: "remove-item",
data: {
uuid: currentActionSheetItem.uuid
}
})
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
//showToast({ message: i18n(lang, "itemDeletedPermanently", true, ["__NAME__"], [currentActionSheetItem.name]) })
}).catch((err) => {
setButtonsDisabled(false)
useStore.setState({ fullscreenLoadingModalVisible: false })
showToast({ message: err.toString() })
})
}} />
</Dialog.Container>
)
}
</>
)
})
Example #17
Source File: index.js From frontend-course with MIT License | 5 votes |
Card = memo(CardComponent)
Example #18
Source File: Header.js From instaclone with Apache License 2.0 | 5 votes |
Header = memo(({ currentUser }) => {
const [shouldMinimizeHeader, setShouldMinimizeHeader] = useState(false);
const {
location: { pathname },
} = useHistory();
// Shrink header height and remove logo on scroll
useScrollPositionThrottled(({ currentScrollPosition }) => {
if (window.outerWidth > 600) {
setShouldMinimizeHeader(currentScrollPosition > 100);
}
});
const headerClassNames = classNames({
header: true,
'header--small': shouldMinimizeHeader,
});
return (
<header className={headerClassNames}>
<div className="header__content">
<Link to="/" className="header__logo">
<div className="header__logo-image">
<LogoCamera />
</div>
<div className="header__logo-header">
<h3 className="heading-logo">Instaclone</h3>
</div>
</Link>
<SearchBox />
<div className="header__icons">
{currentUser ? (
<Fragment>
<Link to="/explore">
<Icon
icon={pathname === '/explore' ? 'compass' : 'compass-outline'}
/>
</Link>
<NotificationButton />
<Link to={'/' + currentUser.username}>
<Icon
icon={
pathname === '/' + currentUser.username
? 'person-circle'
: 'person-circle-outline'
}
/>
</Link>
<NewPostButton />
</Fragment>
) : (
<Fragment>
<Link style={{ marginRight: '1rem' }} to="/login">
<Button>Log In</Button>
</Link>
<Link to="/signup">
<h3 className="heading-3 heading--button color-blue">
Sign Up
</h3>
</Link>
</Fragment>
)}
</div>
</div>
</header>
);
})
Example #19
Source File: index.js From strapi-molecules with MIT License | 5 votes |
Memoized = memo(Header, isEqualFastCompare)
Example #20
Source File: Color.js From Learning-Redux with MIT License | 5 votes |
Trash = memo(FaTrash)
Example #21
Source File: PostList.js From ra-data-django-rest-framework with MIT License | 5 votes |
PostListBulkActions = memo(props => (
<Fragment>
<ResetViewsButton {...props} />
<BulkDeleteButton {...props} />
<BulkExportButton {...props} />
</Fragment>
))
Example #22
Source File: ScrollToBottom.jsx From react-sendbird-messenger with GNU General Public License v3.0 | 5 votes |
MemoizedScrollToBottom = memo(ScrollToBottom)
Example #23
Source File: Level.js From covid19india-react with MIT License | 5 votes |
LevelItem = memo(PureLevelItem)
Example #24
Source File: DynamicCovInce.jsx From covince with MIT License | 5 votes |
UI = memo(lazy(() => import('./components/UI')))
Example #25
Source File: AudioPlayer.js From react-sample-projects with MIT License | 5 votes |
AudioPlayer = memo(AudioPlayerComp)
Example #26
Source File: index.js From ReactSourceCodeAnalyze with MIT License | 5 votes |
MemoizedStatefulClass = memo(StatefulClass)
Example #27
Source File: FolioRecordTypeField.js From ui-data-export with Apache License 2.0 | 5 votes |
FolioRecordTypeField = memo(({
initiallyDisabledRecordTypes,
onTypeDisable,
}) => {
const [touched, setTouched] = useState(false);
const [disabledTypes, setDisabledTypes] = useState({
[FOLIO_RECORD_TYPES.SRS.type]: false,
[FOLIO_RECORD_TYPES.INSTANCE.type]: false,
...initiallyDisabledRecordTypes,
});
const handleRecordTypeChange = useCallback(({ target: { checked } }, { value }) => {
setTouched(true);
const isFieldCanBeDisabled = disabledTypes[value] !== undefined;
if (isFieldCanBeDisabled) {
setDisabledTypes({
...disabledTypes,
[RECORD_TYPES_DISABLING_MAPPING[value]]: checked,
});
}
}, [disabledTypes]);
useEffect(() => {
onTypeDisable(disabledTypes);
}, [disabledTypes, onTypeDisable]);
return (
<div
className={css.folioRecordTypeContainer}
data-test-folio-record-type
>
<Label
htmlFor="folio-record-type"
required
data-test-folio-record-type-label
>
<FormattedMessage id="stripes-data-transfer-components.folioRecordType" />
</Label>
<CheckboxGroupField
id="folio-record-type"
name="recordTypes"
options={RECORD_TYPES}
disabledFields={disabledTypes}
onChange={handleRecordTypeChange}
/>
<div
role="alert"
data-test-folio-record-type-error
>
<Field
name="recordTypes"
component={({ meta }) => {
if ((touched || meta.touched) && meta.error) {
return <span className={css.error}>{meta.error}</span>;
}
if (meta.submitError) {
return <span className={css.error}>{meta.submitError}</span>;
}
return null;
}}
/>
</div>
</div>
);
})
Example #28
Source File: ImageView.js From label-studio-frontend with Apache License 2.0 | 5 votes |
Region = memo(({ region, showSelected = false }) => {
return useObserver(() => region.inSelection !== showSelected ? null : Tree.renderItem(region, false));
})
Example #29
Source File: MapPopup.jsx From frontend with MIT License | 5 votes |
MapPopup = memo(({ anchorEl, regionName, handleClose, elevation, ...popupProps }) => {
const classes = useMapPopupStyles();
const { region, needs } = mockData;
const calculateProgressBarWidth = (mainParameter, ...other) => `${mainParameter} * (100% - 12px) / (${mainParameter} + ${other[0]} + ${other[1]})`
return (
<Popover
className={classes.root}
anchorEl={anchorEl}
open={!!anchorEl}
getContentAnchorEl={null}
onClose={handleClose}
elevation={0}
anchorOrigin={{
vertical: 'center',
horizontal: 'center',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
{...popupProps}
>
<Box display='flex' flexDirection='column' p={2}>
<Box display='flex' justifyContent='space-between' minWidth='200px' >
<Typography className={classes.heading}>{regionName || '-'}</Typography>
<Box ml={2}>
<Typography className={classes.heading}>{region?.cases || '-'}</Typography>
</Box>
</Box>
<Box display='flex' height='34px' width='100%' py={1.75}>
<Box height='6px' width={`calc(${calculateProgressBarWidth(region?.cases, region?.recovered, region?.deaths)})`} mr={0.75} borderRadius={18} bgcolor='#FEAA53' />
<Box height='6px' width={`calc(${calculateProgressBarWidth(region?.recovered, region?.cases, region?.deaths)})`} mr={0.75} borderRadius={18} bgcolor='#2ED47A' />
<Box height='6px' width={`calc(${calculateProgressBarWidth(region?.deaths, region?.cases, region?.recovered)})`} borderRadius={18} bgcolor='#707683' />
</Box>
<Box>
<List disablePadding>
<ListItem disableGutters className={classes.casesListItem}>
<Box height='8px' width='8px' mr={1} borderRadius='50%' bgcolor='#FEAA53' />
<ListItemText disableTypography className={classes.casesListItemText}>{mapPopup.cases}</ListItemText>
<ListItemText disableTypography className={classes.casesListItemTextCount}>{region?.cases || '-'}</ListItemText>
</ListItem>
<ListItem disableGutters className={classes.casesListItem}>
<Box height='8px' width='8px' mr={1} borderRadius='50%' bgcolor='#2ED47A' />
<ListItemText disableTypography className={classes.casesListItemText}>{mapPopup.recovered}</ListItemText>
<ListItemText disableTypography className={classes.casesListItemTextCount}>{region?.recovered || '-'}</ListItemText>
</ListItem>
<ListItem disableGutters className={classes.casesListItem}>
<Box height='8px' width='8px' mr={1} borderRadius='50%' bgcolor='#707683' />
<ListItemText disableTypography className={classes.casesListItemText}>{mapPopup.deaths}</ListItemText>
<ListItemText disableTypography className={classes.casesListItemTextCount}>{region?.deaths || '-'}</ListItemText>
</ListItem>
</List>
</Box>
<Divider className={classes.divider} />
<Box>
<List className={classes.medicineList} disablePadding>
{needs?.map(item => (
<ListItem key={item?.id || item?.type + item?.count} disableGutters>
<SvgIcon viewBox='0 0 36 36' className={classes.listItemIcon}>
<path d={medicineIcons[item?.type.toLowerCase()] || medicineIcons.other} fill="white" />
</SvgIcon>
<ListItemText
primary={medicine[item?.type.toLowerCase()] || item?.type}
secondary={item?.count}
primaryTypographyProps={{ style: primaryTypographyStyle }}
secondaryTypographyProps={{ style: secondaryTypographyStyle }} />
</ListItem>
))}
</List>
</Box>
</Box>
</Popover >
);
})