Skip to content

Commit

Permalink
refactor: useLayoutEffect instead of useEffect
Browse files Browse the repository at this point in the history
  • Loading branch information
kKaskak committed Nov 24, 2023
1 parent 4850449 commit c6f8460
Showing 1 changed file with 6 additions and 18 deletions.
24 changes: 6 additions & 18 deletions src/routes/MetaDetails/StreamsList/StreamsList.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ const StreamsList = ({ className, video, ...props }) => {
const { core } = useServices();
const [selectedAddon, setSelectedAddon] = React.useState(ALL_ADDONS_KEY);
const streamsContainerRef = React.useRef(null);
const scrollHeightRef = React.useRef(null);
const [isScrollable, setIsScrollable] = React.useState(false);
const [showBackToTop, setShowBackToTop] = React.useState(false);
const onAddonSelected = React.useCallback((event) => {
setSelectedAddon(event.value);
}, []);
Expand Down Expand Up @@ -79,25 +79,13 @@ const StreamsList = ({ className, video, ...props }) => {
onSelect: onAddonSelected
};
}, [streamsByAddon, selectedAddon]);
const handleScroll = () => {
if (streamsContainerRef.current) {
const { scrollTop, scrollHeight, clientHeight } = streamsContainerRef.current;
const isScrollable = scrollHeight - clientHeight > 0;
setShowBackToTop(scrollTop > 50);
setIsScrollable(isScrollable);
}
};
React.useEffect(() => {
React.useLayoutEffect(() => {
const container = streamsContainerRef.current;
handleScroll();
if (container) {
container.addEventListener('scroll', handleScroll);
scrollHeightRef.current = container.scrollHeight;
const isScrollable = scrollHeightRef.current > container.clientHeight;
setIsScrollable(isScrollable);
}
return () => {
if (container) {
container.removeEventListener('scroll', handleScroll);
}
};
}, [streamsByAddon, selectedAddon]);

const scrollToTop = () => {
Expand Down Expand Up @@ -173,7 +161,7 @@ const StreamsList = ({ className, video, ...props }) => {
isScrollable && countLoadingAddons === 0 ?
<React.Fragment>
<hr className={styles['line']} />
<div className={classnames(styles['to-top-wrapper'], showBackToTop ? styles['active'] : null)} onClick={scrollToTop}>
<div className={classnames(styles['to-top-wrapper'], isScrollable ? styles['active'] : null)} onClick={scrollToTop}>
<Icon className={styles['icon']} name={'chevron-up'} />
<div className={styles['label']}>Back to Top</div>
</div>
Expand Down

0 comments on commit c6f8460

Please sign in to comment.