Skip to main content

React Hooks for PnP Modal SDK

Web3Auth provides essential React hooks for Web3Auth Modal SDK for managing authentication, chain configuration, and user interactions within your application. These hooks can be directly imported from the @web3auth/modal-react-hooks package. Here's an example of how to import them:

import { useWeb3Auth } from "@web3auth/modal-react-hooks";

For more information on React hooks, refer to the official React documentation.

Available Hooks

  • useWeb3Auth: Provides access to the Web3Auth context initialized via the Web3AuthProvider component.

Hook Context Interface

ParameterDescription
isConnectedIndicates whether a user is currently logged in or not.
providerThe current provider, or null if not connected.
userInfoInformation about the logged-in user.
isMFAEnabledIndicates whether Multi-Factor Authentication (MFA) is enabled or not.
isInitializedIndicates whether Web3Auth has been initialized or not.
statusThe current status of Web3Auth. Can take the following values: NOT_READY, READY, CONNECTING, CONNECTED, DISCONNECTED, ERRORED.
enableMFA(params?)Enables Multi-Factor Authentication for the user. Returns a Promise.
logout(params?)Logs out the user, with an optional cleanup parameter. Returns a Promise.
addAndSwitchChainAdds and switches to a new blockchain. Takes chainConfig of type CustomChainConfig as a parameter. Returns a Promise.
addPluginAdds a plugin to the Web3Auth instance. Takes a plugin of type IPlugin as a parameter.
getPluginRetrieves a plugin by name. Takes pluginName of type string as parameter. Returns an IPlugin or null.
authenticateUserRetrieves the idToken for the logged-in user. Returns a Promise.
addChainAdds a new blockchain configuration. Takes chainConfig of type CustomChainConfig as a parameter. Returns a Promise.
switchChainSwitches to a specified blockchain by chain ID. Takes params of type { chainId: string } as a parameter. Returns a Promise.

Web3AuthProvider

The Web3AuthProvider component wraps the main component and injects the Web3Auth-related context into it. It takes the following properties as its context:

ParameterDescription
web3AuthOptionsConfiguration options for Web3Auth.
adaptersAn array of adapters for connecting to different blockchain networks.
pluginsAn array of plugins to add additional functionality to Web3Auth.
info

Please check out the PnP Modal SDK references for interfaces for the inner parameters.

Shared Methods Descriptions

Once you've installed and successfully initialized Web3Auth, you can use it to authenticate your users. Further, you can use the native provider given by Web3Auth to connect the users to the respective blockchain network.

Natively, the instance of Web3Auth (referred to as web3auth in our examples) returns the following functions:

  • init() - Initializes the Web3Auth instance.

    await init();

    Returns:

    init(): Promise<void>;
  • connect() - Showing the Modal and Logging in the User.

    await connect();

    Returns:

    connect(): Promise<IProvider | null>;

    On successful login, the connect function returns an IProvider instance. You can use this provider to connect your user to the blockchain and make transactions.

  • provider() - Returns the native provider that can be used to make different blockchain transactions. Returns:

    get provider(): IProvider | null;
  • connected() - Returns true or false depending on whether the web3auth instance is available or not. Returns:

    get connected(): boolean;
  • getUserInfo() - Getting the User's Information.

    const userInfo = await getUserInfo();
  • authenticateUser() - Getting the idToken from Web3Auth.

    const idToken = await authenticateUser();
  • addChain() - Add chain config details to the connected adapter.

    await addChain(chainConfig);
  • switchChain() - Switch chain as per chainId already added to chain config.

    await switchChain({ chainId: "0x1" });
  • getAdapter() - Get the connected adapter instance.

    const adapter = await getAdapter(adapterName);
  • configureAdapter() - Configure the adapter instance.

    await configureAdapter(adapterConfig);
  • clearCache() - Clear the cache.

    await clearCache();
  • addPlugin() - Add a plugin to Web3Auth.

    await addPlugin(plugin);
  • logout() - Logging out the User.

    await logout();

Example Usage

web3AuthProviderProps.ts
import { Web3AuthContextConfig } from "@web3auth/modal-react-hooks";
import { Web3AuthOptions } from "@web3auth/modal";
import { EthereumPrivateKeyProvider } from "@web3auth/ethereum-provider";
import { CHAIN_NAMESPACES, WEB3AUTH_NETWORK } from "@web3auth/base";
import { OpenloginAdapter } from "@web3auth/openlogin-adapter";
import { WalletServicesPlugin } from "@web3auth/wallet-services-plugin";

const chainConfig = {
chainId: "0xaa36a7", // for wallet connect make sure to pass in this chain in the loginSettings of the adapter.
displayName: "Ethereum Sepolia",
chainNamespace: CHAIN_NAMESPACES.EIP155,
tickerName: "Ethereum Sepolia",
ticker: "ETH",
rpcTarget: "https://rpc.ankr.com/eth_sepolia",
blockExplorerUrl: "https://sepolia.etherscan.io",
logo: "https://cryptologos.cc/logos/ethereum-eth-logo.png",
};

const privateKeyProvider = new EthereumPrivateKeyProvider({
config: {
chainConfig,
},
});

const web3AuthOptions: Web3AuthOptions = {
clientId:
"BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ",
web3AuthNetwork: WEB3AUTH_NETWORK.SAPPHIRE_MAINNET,
privateKeyProvider: privateKeyProvider,
};

const openloginAdapter = new OpenloginAdapter();

const walletServicesPlugin = new WalletServicesPlugin({
wsEmbedOpts: {},
walletInitOptions: { whiteLabel: { showWidgetButton: true } },
});

export const web3AuthContextConfig: Web3AuthContextConfig = {
web3AuthOptions,
adapters: [openloginAdapter],
plugins: [walletServicesPlugin],
};
App.tsx
import React from "react";
import { Web3AuthProvider, useWeb3Auth } from "@web3auth/modal-react-hooks";
import { web3AuthContextConfig } from "./web3AuthProviderProps";

const App = () => {
const {
connect,
logout,
isConnected,
enableMFA,
addAndSwitchChain,
authenticateUser,
addChain,
switchChain,
} = useWeb3Auth();

return (
<Web3AuthProvider config={web3AuthContextConfig}>
<div>
{isConnected ? (
<>
<button onClick={logout}>Logout</button>
<button onClick={enableMFA}>Enable MFA</button>
<button
onClick={() =>
addAndSwitchChain({
chainId: "0x89",
rpcTarget: "https://rpc.ankr.com/polygon",
displayName: "Polygon Mainnet",
ticker: "MATIC",
})
}
>
Add and Switch Chain
</button>
<button onClick={authenticateUser}>Authenticate User</button>
<button
onClick={() =>
addChain({
chainId: "0x89",
rpcTarget: "https://rpc.ankr.com/polygon",
displayName: "Polygon Mainnet",
ticker: "MATIC",
})
}
>
Add Chain
</button>
<button onClick={() => switchChain({ chainId: "0x89" })}>Switch Chain</button>
</>
) : (
<button onClick={connect}>Login</button>
)}
</div>
</Web3AuthProvider>
);
};

export default App;