Reactjs Reusable component not updated when one of dependency library used at useEffect() change

82 views Asked by At

I've a nextjs custom component that adds the locale before the pathname of the page when clicked and adds custom style for the active link..

here is the component

"use client";

import { useLocale } from "next-intl";
import Link from "next/link";
import { usePathname } from "next/navigation";
import React, { useEffect, useState } from "react";

export default function RoutingLink({
    children,
    href,
    className,
    activeClass
}: {
    children: React.ReactNode;
    href: string;
    className?: string;
    activeClass?: string;
}) {
    const currentLocale = useLocale();
    const pathname = usePathname();
    const [isLinkActive, setIsLinkActive] = useState<boolean>(false);
    useEffect(
        () => {
            if (pathname.slice(1) === href) {
                setIsLinkActive(true);
            }

            () => {
                setIsLinkActive(false);
            };
        },
        [pathname]
    );

    function handleActiveClass() {
        if (isLinkActive) {
            if (activeClass) {
                return activeClass;
            } else {
                return "text-primaryHover";
            }
        } else {
            return "";
        }
    }

    return (
        <Link href={`/${currentLocale}/${href}`} className={`${className} ${handleActiveClass()}`}>
            {children}
        </Link>
    );
}

the problem happened after I created a sidebar tab component *please have a look at the screenshot * Nav Tabs with different hrefs, when I click at one link it becomes active and style changes but after I click at another one the previous link still have the active style as well.

I've tried to use useEffect() passing current pathname as dependency library to it, so that whenever the url is changed the active class should be changed and callback function should be called so that active style disappears from previous link.

1

There are 1 answers

0
Cam Hoang On

I think Tailwind won't recall the function even if your component re-renders. Moreover, if there are multiple RoutingLinks on the same page, then the old RoutingLink is still mounted when someone clicks on another link - so the callback function on useEffect won't get called.

Try refactoring like so:

const pathname = usePathname();
const isActive = pathname.slice(1) === href;
const linkClass = isActive ? activeClass || "text-primaryHover" : "";

return (
        <Link href={`/${currentLocale}/${href}`} className={`${className} ${linkClass}`}>
            {children}
        </Link>
);