From 2613a5cec770ad47c41edc5841ad853006773e92 Mon Sep 17 00:00:00 2001 From: Luis Alvarez Date: Thu, 21 Jan 2021 10:44:59 -0500 Subject: [PATCH] Improve navbar performance --- components/common/Navbar/Navbar.tsx | 93 ++++++++++--------------- components/common/Navbar/NavbarRoot.tsx | 33 +++++++++ 2 files changed, 70 insertions(+), 56 deletions(-) create mode 100644 components/common/Navbar/NavbarRoot.tsx diff --git a/components/common/Navbar/Navbar.tsx b/components/common/Navbar/Navbar.tsx index d2d2b2d79..b2a372f66 100644 --- a/components/common/Navbar/Navbar.tsx +++ b/components/common/Navbar/Navbar.tsx @@ -1,66 +1,47 @@ -import { FC, useState, useEffect } from 'react' +import { FC } from 'react' import Link from 'next/link' -import s from './Navbar.module.css' import { Logo, Container } from '@components/ui' import { Searchbar, UserNav } from '@components/common' -import cn from 'classnames' -import throttle from 'lodash.throttle' +import NavbarRoot from './NavbarRoot' +import s from './Navbar.module.css' -const Navbar: FC = () => { - const [hasScrolled, setHasScrolled] = useState(false) - - useEffect(() => { - const handleScroll = throttle(() => { - const offset = 0 - const { scrollTop } = document.documentElement - const scrolled = scrollTop > offset - setHasScrolled(scrolled) - }, 200) - - document.addEventListener('scroll', handleScroll) - return () => { - document.removeEventListener('scroll', handleScroll) - } - }, []) - - return ( -
- -
-
- - - - +const Navbar: FC = () => ( + + +
+
+ + + + + +
- -
- -
- -
- -
+ + Clothes + + + Accessories + +
-
- +
+
- -
- ) -} + +
+ +
+
+ +
+ +
+ + +) export default Navbar diff --git a/components/common/Navbar/NavbarRoot.tsx b/components/common/Navbar/NavbarRoot.tsx new file mode 100644 index 000000000..2eb8c5429 --- /dev/null +++ b/components/common/Navbar/NavbarRoot.tsx @@ -0,0 +1,33 @@ +import { FC, useState, useEffect } from 'react' +import throttle from 'lodash.throttle' +import cn from 'classnames' +import s from './Navbar.module.css' + +const NavbarRoot: FC = ({ children }) => { + const [hasScrolled, setHasScrolled] = useState(false) + + useEffect(() => { + const handleScroll = throttle(() => { + const offset = 0 + const { scrollTop } = document.documentElement + const scrolled = scrollTop > offset + + if (hasScrolled !== scrolled) { + setHasScrolled(scrolled) + } + }, 200) + + document.addEventListener('scroll', handleScroll) + return () => { + document.removeEventListener('scroll', handleScroll) + } + }, [hasScrolled]) + + return ( +
+ {children} +
+ ) +} + +export default NavbarRoot