skip to Main Content

Why doesn’t this cause any logs?

addEventListener("hashchange", () => console.log("hash changed"))
history.pushState({}, "", "/#/test")
history.pushState({}, "", "#/test")

Also, in React, when using window.location.href as a dependency in useEffect, a url change doesn’t trigger the effect. What’s going on?

2

Answers


  1. Basically, pushState() never causes a hashchange event to be fired.
    And you should use window.location.hash in useEffect

    Login or Signup to reply.
  2. in react , using window.location.href as a dependency in uuseEffect won’t trigger the effect because react compares dependencies using strict equality. to make the effect respond to url changes, use window.location.hash like this:
    history.pushState({}, "", "/");
    location.hash = "#test";

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search