Skip to content

Instantly share code, notes, and snippets.

@hexcowboy
Last active April 26, 2023 21:29
Show Gist options
  • Save hexcowboy/bcb33b32857ff28433c4727b21671617 to your computer and use it in GitHub Desktop.
Save hexcowboy/bcb33b32857ff28433c4727b21671617 to your computer and use it in GitHub Desktop.
Next.js 13 App Directory with Wagmi - `Warning: Expected server HTML to contain a matching <div> in <div>.`

Warning: Expected server HTML to contain a matching <div> in <div>.

You will likely see this error if you ever try to use Wagmi in your Dapp. This solution actually works for any reason if you're seeing the error above.

This article explains the issue in a bit more depth. This gist will give you a simple solution.

Using Wagmi values

Using Wagmi hooks like useAccount() or similar will cause your app to render differently on the client than it does on the server. To make them only run on the client, use this utility component.

src/helpers/client.tsx

"use client";

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

interface Props {
  children: JSX.Element | null;
}

const Client = ({ children }: Props) => {
  const [hasMounted, setHasMounted] = useState(false);

  useEffect(() => {
    setHasMounted(true);
  }, []);

  if (!hasMounted) return null;

  return children;
};

export default Client;

export const withClient = (Component: () => JSX.Element) => {
  const ClientOnly = () => (
    <Client>
      <Component />
    </Client>
  );
  return ClientOnly;
};

Usage

Either use the <Client> component or use the withClient helper method to export your component.

Usage 1

import { useAccount } from "wagmi";

import Client from "@/helpers/client";

const MyComponent = () => {
  const { isConnecting } = useAccount();
  
  return (
    <Client>
      {isConnecting ? (
        You are connecting...
      ) : (
        You are done connecting.
      )}
    </Client>
  );
}

export default MyComponent;

Usage 2

import { useAccount } from "wagmi";

import { withClient } from "@/helpers/client";

const MyComponent = () => {
  const { isConnecting } = useAccount();
  
  return (
    {isConnecting ? (
      You are connecting...
    ) : (
      You are done connecting.
    )}
  );
}

export default withClient(MyComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment