Skip to content
Docs
/
Hooks
/
useBlockNumber

useBlockNumber

Hook for fetching the current block number.

import { useBlockNumber } from 'wagmi'

Usage

import { useBlockNumber } from 'wagmi'

function App() {
  const { data, isError, isLoading } = useBlockNumber()

  if (isLoading) return <div>Fetching block number…</div>
  if (isError) return <div>Error fetching block number</div>
  return <div>Block number: {data}</div>
}

Return Values

{
  data?: number
  error?: Error
  isError: boolean
  isFetched: boolean
  isFetching: boolean
  isIdle: boolean
  isLoading: boolean
  isRefetching: boolean
  isStale: boolean
  isSuccess: boolean
  refetch: (options: {
    throwOnError: boolean
    cancelRefetch: boolean
  }) => Promise<number>
  status: 'idle' | 'error' | 'loading' | 'success'
}

Configuration

watch (optional)

Watches and refreshes data for new blocks.

import { useBlockNumber } from 'wagmi'

function App() {
  const blockNumber = useBlockNumber({
    watch: true,
  })
}

cacheTime (optional)

Time (in ms) which the data should remain in the cache. Defaults to 0.

import { useBlockNumber } from 'wagmi'

function App() {
  const blockNumber = useBlockNumber({
    cacheTime: 2_000,
  })
}

enabled (optional)

Set this to false to disable this query from automatically running. Defaults to true.

import { useBlockNumber } from 'wagmi'

function App() {
  const blockNumber = useBlockNumber({
    enabled: false,
  })
}

staleTime (optional)

Time (in ms) after data is considered stale. If set to Infinity the data will never be considered stale. Defaults to 0.

import { useBlockNumber } from 'wagmi'

function App() {
  const blockNumber = useBlockNumber({
    staleTime: 2_000,
  })
}

suspense (optional)

Set this to true to enable suspense mode.

import { useBlockNumber } from 'wagmi'

function App() {
  const blockNumber = useBlockNumber({
    suspense: true,
  })
}

onSuccess (optional)

Function to invoke when fetching new data is successful.

import { useBlockNumber } from 'wagmi'

function App() {
  const blockNumber = useBlockNumber({
    onSuccess(data) {
      console.log('Success', data)
    },
  })
}

onError (optional)

Function to invoke when an error is thrown while fetching new data.

import { useBlockNumber } from 'wagmi'

function App() {
  const blockNumber = useBlockNumber({
    onError(error) {
      console.log('Error', error)
    },
  })
}

onSettled (optional)

Function to invoke when fetching is settled (either successfully fetched, or an error has thrown).

import { useBlockNumber } from 'wagmi'

function App() {
  const blockNumber = useBlockNumber({
    onSettled(data, error) {
      console.log('Settled', { data, error })
    },
  })
}