{ const [isVisible, setIsVisible] = useState(false); useEffect(() => { const handleS" /> { const [isVisible, setIsVisible] = useState(false); useEffect(() => { const handleS" /> { const [isVisible, setIsVisible] = useState(false); useEffect(() => { const handleS"/>

How will handScroll work when it is getting removed by cleanup function

15 views Asked by At
import { useState, useEffect } from "react";

const Navbar = () => {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY >= 50) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <nav
      className={`fixed top-0 left-0 right-0 z-50 py-4 transition-opacity duration-300 backdrop-blur-sm backdrop-brightness-120 ${
        isVisible ? "opacity-100" : "opacity-0 hidden"
      }`}
    >
      <div className="container mx-auto flex justify-end">
        <div className="flex items-center space-x-4">
          <a href="#" className="text-primary hover:text-gray-900">
            Home
          </a>
          <a href="#" className="text-primary hover:text-gray-900">
            About
          </a>
          <a href="#" className="text-primary hover:text-gray-900">
            Projects
          </a>
          <a href="#" className="text-primary hover:text-gray-900">
            Contact
          </a>
        </div>
      </div>
    </nav>
  );
};

export default Navbar;

I would like to know how is the handle Scroll function still working even after the component is unmounted?

I am not sure if I understood the process, can someone shed some light on this? I do understand the lifecycle of react component but inside useEffect is where I am confused, specially return in useEffect`

0

There are 0 answers