Custom React Hook to resolve ENS name and avatar using EthersJs

Learn how to fetch ENS name and avatar for any ENS domain using EthersJs.

Prerequisites

Terminal
$npm install ethers

Snippet

import { ethers } from "ethers";
import { useEffect, useState } from "react";

const useENS = (address: string) => {
  const [ensName, setENSName] = useState<string | null>(null);
  const [ensAvatar, setENSAvatar] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const resolveENS = async () => {
      if (address && ethers.utils.isAddress(address)) {
        try {
          setLoading(true);
          const provider = new ethers.providers.getDefaultProvider();

          const ensName = await provider.lookupAddress(address);

          const resolver = ensName ? await provider.getResolver(ensName) : null;
          const avatar = resolver ? await resolver.getAvatar() : null;

          setENSName(ensName);
          setENSAvatar(avatar.url);
        } finally {
          setLoading(false);
        }
      }
    };
    resolveENS();
  }, [address]);

  return { ensName, ensAvatar, loading };
};

export default useENS;
1
Initialize web3 provider

The provider is the abstract connection to Ethereum network, it can be anything of your choice, you can also use JsonRpcProvider, InfuraProvider and more.

More about Providers

2
Lookup with address

We are now performing a reverse lookup of the address in ENS using the Reverse Registrar.

3
ENS Avatar

Using the resolver from ENS name, we can also get the user's avatar that they recorded in ENS protocol.

Usage

const { ensName, ensAvatar, loading } = useENS(address);

If the user pointed their address to a .eth domain, it will lookup for the name of the domain else it will return null, same applies to the avatar.