Read contract state

Read onchain data from any contract on any chain.

Generic Contract Read

Reading contract state in react is done via the useReadContract hook. The hook returns a React Query data, isLoading, and other useful state that you can use to render your component.

import { getContract } from "thirdweb";
import { useReadContract } from "thirdweb/react";
const contract = getContract({
client,
chain,
address: "0x...",
});
const MyComponent = () => {
const { data, isLoading } = useReadContract({
contract,
method: "function tokenURI(uint256 tokenId) returns (string)",
params: [1n],
});
};

Using Extensions

Extensions are a way to make complex queries from a contract in a type-safe way with a simple API.

import { getContract } from "thirdweb";
import { useReadContract } from "thirdweb/react";
import { getOwnedNFTs } from "thirdweb/extensions/erc721";
const contract = getContract({
client,
chain,
address: "0x...",
});
const MyComponent = () => {
const ownedNFTs = useReadContract(getOwnedNFTs, {
contract,
address: "0x...",
});
};

Check out all the available extensions for more details.

Generic Contract Events

Query and listen to contract events with the useContractEvents hook.

import { useContractEvents } from "thirdweb/react";
import { prepareEvent } from "thirdweb";
const myEvent = prepareEvent({
signature: "event MyEvent(uint256 myArg)",
});
const { data: events } = useContractEvents({
contract,
eventName: [myEvent],
});

or with extensions:

import { useContractEvents } from "thirdweb/react";
import { tokensClaimedEvent } from "thirdweb/extensions/erc721";
const { data: events } = useContractEvents({
contract,
events: [tokensClaimedEvent()],
});

API References

Check out the contract hooks reference for more details.