Removing useEffects that have no side effect and alter the state.

This commit is contained in:
Gabriel 2023-11-13 13:59:12 -03:00
parent 2fe1527bea
commit b38b40aa4e
3 changed files with 19 additions and 22 deletions

View File

@ -4,15 +4,10 @@ import clsx from 'clsx';
import { Menu } from 'lib/shopify/types';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useState } from 'react';
const FooterMenuItem = ({ item }: { item: Menu }) => {
const pathname = usePathname();
const [active, setActive] = useState(pathname === item.path);
useEffect(() => {
setActive(pathname === item.path);
}, [pathname, item.path]);
const active = pathname === item.path;
return (
<li>

View File

@ -16,6 +16,17 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
const openMobileMenu = () => setIsOpen(true);
const closeMobileMenu = () => setIsOpen(false);
const [prevPathname, setPrevPathname] = useState(pathname);
const [prevSearchParams, setPrevSearchParams] = useState(searchParams);
if (prevPathname !== pathname) {
setPrevPathname(pathname);
setIsOpen(false);
}
if (!Object.is(prevSearchParams, searchParams)) {
setIsOpen(false);
setPrevSearchParams(searchParams);
}
useEffect(() => {
const handleResize = () => {
if (window.innerWidth > 768) {
@ -26,10 +37,6 @@ export default function MobileMenu({ menu }: { menu: Menu[] }) {
return () => window.removeEventListener('resize', handleResize);
}, [isOpen]);
useEffect(() => {
setIsOpen(false);
}, [pathname, searchParams]);
return (
<>
<button

View File

@ -10,10 +10,16 @@ import { FilterItem } from './item';
export default function FilterItemDropdown({ list }: { list: ListItem[] }) {
const pathname = usePathname();
const searchParams = useSearchParams();
const [active, setActive] = useState('');
const [openSelect, setOpenSelect] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const active =
list.findLast(
(listItem: ListItem) => (
('path' in listItem && pathname === listItem.path) ||
('slug' in listItem && searchParams.get('sort') === listItem.slug)
))?.title ?? '';
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
@ -25,17 +31,6 @@ export default function FilterItemDropdown({ list }: { list: ListItem[] }) {
return () => window.removeEventListener('click', handleClickOutside);
}, []);
useEffect(() => {
list.forEach((listItem: ListItem) => {
if (
('path' in listItem && pathname === listItem.path) ||
('slug' in listItem && searchParams.get('sort') === listItem.slug)
) {
setActive(listItem.title);
}
});
}, [pathname, list, searchParams]);
return (
<div className="relative" ref={ref}>
<div