Search code examples
javascriptreactjsperformanceuser-experienceapexcharts

How to fix React Apex Chart initial mount delay?


I am using React Apex chart library in my project.I've figured that the library charts have a small delay before rendering on initial mount.

This issue harms the UX because the component that renders ApexCharts won't be displayed until after the delay.

import React from "react";
import Chart from "react-apexcharts";

function MixedChart() {
    const data = {
      options: {
        chart: {
          id: "basic-bar"
        },
        xaxis: {
          categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
        }
      },
      series: [
        {
          name: "series-1",
          data: [30, 40, 45, 50, 49, 60, 70, 91]
        }
      ]
    };

    return (
         <div className="mixed-chart">
           <Chart
             options={data.options}
             series={data.series}
             type="bar"
             width="500"
           />
         </div>
    );

}

export default MixedChart;

Is there a way to fix this ?


Solution

  • I figured out the solution.

    To avoid the app rendering nothing in that delay and have a better UX, you can use a set timeout inside useEffect hook to update a state after the chart's initial mount.

    const [display, setDisplay] = useState(false);
    
    useEffect(() => {
       setTimeout(() => setDisplay(true), 1);
    }, [])
    
    if(!display) {
     return <></>;
    }
    
    return (
      <div className="mixed-chart">
        <Chart
          options={data.options}
          series={data.series}
          type="bar"
          width="500"
         />
      </div>);