Skip to main content

useNetwork

info

This hook is deprecated. Use the useChain, useSwitchChain and useChainId hooks instead.

Hook for getting information about the current network and switching to a different network.

Returns an array value containing two elements.

  1. An object containing the following properties:

    • data object contains information about the wallet's current and supported networks.
    • loading indicates if the switch network request is in progress.
    • error holds the Error object if there was an error when attempting to switch network.
  2. A function that can be used to switch to a different network.

import { useNetwork } from "@thirdweb-dev/react";

const [{ data, error, loading }, switchNetwork] = useNetwork();

Usage

import { useNetwork } from "@thirdweb-dev/react";

function App() {
const [{ data, error, loading }, switchNetwork] = useNetwork();

return (
<button
onClick={async () => {
if (!switchNetwork) {
console.log("can not switch network");
return;
}

const result = await switchNetwork(80001);
if (result.data) {
console.log("Switched to Mumbai testnet successfully");
} else {
console.log("Error switching to Mumbai testnet", result.error);
}
}}
>
Switch to Mumbai
</button>
);
}

Return Value

data

If wallet is connected to a network that is one of supportedChains or one of the defaultChains, data object will contain the following:

{
chain: Chain; // The connected network
chains: Chain[]; // All supported networks
}

If wallet is connected to a network that is NOT one of supportedChains or defaultChains, data object will contain the following:

{
// chainId of current connected network + unsupported flag
chain: { chainId: number, unsupported: true };
// All supported networks
chains: Chain[];
}

If wallet is not connected, data object will contain the following:

{
chain: undefined;
chains: []; // Empty array
}
error

error contains an Error object if there was an error when attempting to switch network using the switchNetwork function

undefined if there is no switch network error

Error | undefined;
loading

loading is true when switching network using the switchNetwork function, and false otherwise.

boolean;
switchNetwork

switchNetwork is a function that can be used to switch to a different network. It takes a chainId as an argument and returns a promise that resolves to an object containing data and error properties.

If switching network was successful, data will contain the new network information. and error will be undefined. If switching network failed, data will be undefined and error will contain an Error object.

switchNetwork is undefined if not connected to a wallet or if the connected wallet does not allow programmatic switching.

type SwitchNetwork = undefined | (chainId: number) => Promise<
| {
data: Chain | undefined;
error: undefined;
}
| {
data: undefined;
error: Error;
}>