0

This code was being used in my project which took the page to top whenever route changed and also when you click on a link of the same route you are on. I referred this answer to write the code below. The problem with the linked answer was that it didn't take the page to top if you click on a link which has the same route as you are on currently. So I modified it and wrote it like this.

    import React, {useEffect} from 'react'
    import { useLocation } from 'react-router-dom'
    const Scroll2Top = () => {
        const { pathname } = useLocation();
    
        useEffect(() => {
          window.scrollTo(0, 0);
        });
        return null;
    }

export default Scroll2Top

But when I remove the useLocation hook which is not even being used my code stops working. Why is this happening ? Another similar example I came across is

  // not being used but stops working if I remove this
  let history = useNavigate();

  useEffect(() => {
    let termsInput = document.querySelector("#terms > input");
    let claimInput = document.querySelector("#claim > input");

    if (window.location.href.includes("#terms")) {
      termsInput.checked = true;
      claimInput.checked = false;
      
    } else if(window.location.href.includes("#privacy")) {
      termsInput.checked = false;
      claimInput.checked = false;
    }
    else if (window.location.href.includes("#claim")) {
      claimInput.checked = true;
      termsInput.checked = false;
    }
  });

I have no clue why this happens and I was not able to find similar question anywhere on stackoverflow.

heysujal
  • 118
  • 7

1 Answers1

0

Its because you're not providing any dep array for useEffect it means it will run on every render of that component, and when you use useLocation hook it will be called everytime you move between pages which will cause rerender of that component, but if you remove that useLoaction hook there is no factor to cause rerender on that component so useEffect won't run.

heysujal
  • 118
  • 7