• React
  • Hooks
  • useContractEvent

useContractEvent

Hook for subscribing to Contract events.

This is a wrapper around viem's watchContractEvent.

import { useContractEvent } from 'wagmi'

Usage

The following examples use the ENS Registry contract.

import { useContractEvent } from 'wagmi'
 
function App() {
  useContractEvent({
    address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
    abi: ensRegistryABI,
    eventName: 'NewOwner',
    listener(log) {
      console.log(log)
    },
  })
}

The useContractEvent Hook also returns an unwatch function that can be used to unsubscribe from the event. Can be used to clean up the listener after an event is seen.

import { useContractEvent } from 'wagmi'
 
function App() {
  const unwatch = useContractEvent({
    address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
    abi: erc20ABI,
    eventName: 'Transfer',
    listener(log) {
      console.log(log)
      if (log.args.from === '0x...') unwatch?.()
    },
  })
}

Configuration

address (optional)

Contract address. If address is not defined, hook will not run.

import { useContractEvent } from 'wagmi'
 
function App() {
  useContractEvent({
    address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
    abi: ensRegistryABI,
    eventName: 'NewOwner',
    listener(log) {
      console.log(log)
    },
  })
}

abi (optional)

Contract ABI. If abi is not defined, hook will not run.

By defining inline or adding a const assertion to abi, TypeScript will infer the correct types for eventName and listener. See the wagmi TypeScript docs for more information.

import { useContractEvent } from 'wagmi'
 
function App() {
  useContractEvent({
    address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
    abi: ensRegistryABI,
    eventName: 'NewOwner',
    listener(log) {
      console.log(log)
    },
  })
}

eventName (optional)

Name of the event to listen to. If eventName is not defined, hook will not run.

import { useContractEvent } from 'wagmi'
 
function App() {
  useContractEvent({
    address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
    abi: ensRegistryABI,
    eventName: 'NewResolver',
    listener(log) {
      console.log(log)
    },
  })
}

listener

Callback that receives event.

import { useContractEvent } from 'wagmi'
 
function App() {
  useContractEvent({
    address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
    abi: ensRegistryABI,
    eventName: 'NewOwner',
    listener(log) {
      console.log(log)
    },
  })
}

chainId (optional)

Force a specific chain id. The wagmi Client's publicClient must be set up as a chain-aware function for this to work correctly.

import { useContractEvent } from 'wagmi'
 
function App() {
  useContractEvent({
    address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
    abi: ensRegistryABI,
    eventName: 'NewOwner',
    listener(log) {
      console.log(log)
    },
    chainId: 1,
  })
}