usePlug
React Hook for Connecting to the Plug Wallet and Creating Canister Actors
usePlug.ts
usePlug.tsThis file defines a custom React + TypeScript hook that makes it easier to connect a frontend application to the Plug Internet Computer wallet extension, manage its connection state, and create actors for calling canisters.
Global Type Declaration
declare global {
interface Window {
ic?: {
plug?: {
isConnected: () => Promise<boolean> | boolean;
requestConnect: (opts: { ... }) => Promise<boolean>;
createActor: <T>(opts: { canisterId: string; interfaceFactory: any; }) => Promise<T>;
getPrincipal: () => Promise<{ toText: () => string }>;
disconnect?: () => Promise<void>;
};
};
}
}Extends the
Windowinterface to include theic.plugobject provided by the Plug extension.Declares the available Plug methods:
isConnected— Checks if the wallet is connected.requestConnect— Requests user permission to connect.createActor— Creates a typed canister actor from anidlFactory.getPrincipal— Retrieves the user’s principal.disconnect(optional) — Disconnects from the wallet.
Types
PlugState— Holds connection status, principal, and error information.ConnectOptions— Options for connecting to Plug (whitelist, host, timeout, key type).
The usePlug Hook
usePlug HookManages Plug wallet state and provides helper methods for interaction.
State Variables:
available— Whether Plug is installed.connected— Whether the user is connected to the site.principal— The user’s wallet principal (if connected).error— Any error message from recent operations.
1. refresh
Checks if Plug is available and updates connection state.
If connected, retrieves the user’s principal.
Called automatically when the component mounts.
2. connect
Merges
defaultOptsandoptsto form connection settings.Calls
requestConnecton Plug to request access from the user.If approved, updates connection state and retrieves principal.
3. disconnect
Disconnects from the wallet if Plug supports
disconnect.Clears connection state.
4. createActor
Creates a typed canister actor using
idlFactoryandcanisterId.Throws an error if Plug is not connected.
5. getPrincipal
Retrieves the user’s principal in text format.
Throws an error if Plug is not connected.
6. Auto Refresh
Automatically checks Plug status when the hook is first used.
7. Returned API
Returns an object containing:
Current state (
available,connected,principal,error)Methods (
connect,disconnect,refresh,createActor,getPrincipal)
Last updated