Recharts - using the useState hook as part of the Brush's onChange prevents the Brush from changing value

Viewed 859

I'm trying to store the startIndex and endIndex values from the Brush component to state but using the "useState" hook locks the default values into place, meaning the user cannot use the Brush.

The state is successfully being set, on initial load if the user clicks "print dates" an empty string is printed, if they try move the Brush then click "print dates", the default range is printed.

Codesandbox with issue can be found here.

import "./styles.css";
import {
  ResponsiveContainer,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Brush
} from "recharts";
import { useState } from "react";

export default function App() {
  const data = [
    { interval: "2021-01-01", resultCount: 2 },
    { interval: "2021-01-03", resultCount: 7 },
    { interval: "2021-01-05", resultCount: 1 }
  ];

  const [dates, setDates] = useState("");
  const printDates = (d) => console.log(d);
  return (
    <div className="App">
      <button onClick={printDates(dates)}>print dates</button>
      <ResponsiveContainer height={400} width={400}>
        <LineChart data={data}>
          <YAxis
            dataKey="resultCount"
            label={{
              value: "No. of Posts",
              angle: -90,
              position: "insideLeft"
            }}
          />
          <XAxis
            dataKey="interval"
            label={{ value: "Time (day)", position: "bottom" }}
          />
          <CartesianGrid vertical={false} />
          <Line
            strokeWidth={2}
            dataKey="resultCount"
            stroke="#127ABF"
            dot={{ stroke: "#127ABF", strokeWidth: 3, fill: "#127ABF" }}
            isAnimationActive={false}
          />
          <Brush dataKey="interval" onChange={(range) => setDates(range)} />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

1 Answers

For anyone who's interested I've solved this issue by rewriting it all as a class component and not using hooks at all. Haven't figured out the actual issue yet but this is a workaround at least.

Related