Listening to the MetaMask account network changes in React.js app

Viewed 1267

How to detect the automatic change in Metamask wallet Network in react Js and re-render the UI. i.e. If you change Network from Metamask react DAPP, It automatically detects the change in Metamask Network and Update Singer and UI automatically.

1 Answers

  // Detect change in Metamask account
  useEffect(() => {
    if (window.ethereum) {
      window.ethereum.on("chainChanged", () => {
        window.location.reload();
      });
      window.ethereum.on("accountsChanged", () => {
        window.location.reload();
      });
    }
  });

Related