Nextjs : (window is not defined) react-apexcharts

Nextjs : (window is not defined) react-apexcharts

Apex Charts tries to access the window object without checking it is available first, so it does not work in server contexts.
The workaround is to ensure the library is only used in a browser context.

In NextJS, the usual method of ensuring a module only renders on the client is to use next/dyanamic with SSR disabled, but this approach doesn't work in NextJS 13:

// nextjs13 - doesn't work - gives "window is not defined"
"use client";
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });

export default function ApexChart(props: any) {
  return <Chart {...props} />;
}

My current workaround is to import "react-apexcharts" inside a useEffect to force NextJS to only import on the client side:

// nextjs13 - works
"use client";
import { useEffect, useState } from "react";

export default function ApexChart(props: any) {
  const [Chart, setChart] = useState<any>();
  const hasType = typeof props?.type !== "undefined";

  useEffect(() => {
    import("react-apexcharts").then((mod) => {
      setChart(() => mod.default);
    });
  }, []);

  return hasType && Chart && <Chart {...props} />;
}

But in my opinion, I feel this is unnecessary if the Apex Charts library would just check that the window object is available first before trying to access it.