Home > Blockchain >  Rerender a functional React component using useState and ensure useEffect hook executed
Rerender a functional React component using useState and ensure useEffect hook executed

Time:03-02

I have a functional React component which draws a polygon on a canvas. The result looks like this:

enter image description here

My code is (I have left out the irrelevant stuff):

import { useEffect, useState } from "react";

function Plot(props) {
  const [localPolygon, setlocalPolygon] = useState(props.polygon);

  useEffect(() => {
    // in here get the canvas context
    const { context } = getContext();
    // transforms data and draw the polygon on the canvas canvas
  }, [localPolygon]);

  const handleMouseMove = (event) => {
    // making some changes here to localPolgon as user drag
    // then update localPolygon
    setLocalPolygon(localPolygon);
    // I now expect the polygon to change position, but it does not
  };

  return (
    <>
      {" "}
      <canvas
        className="canvas"
        onm ouseMove={(e) => {
          let nativeEvent = e.nativeEvent;
          handleMouseMove(nativeEvent);
        }}
      />
    </>
  );
}

export default Plot;

So the component loads, and in useEffect I do some transformation of data and draw it on the canvas. This works fine. I now want to drag the polygon. I'm able to get the new coordinates as I drag, and update localPolygon with setLocalPolygon(localPolygon). I can see it getting updated, but the polygon is not changing position because the component does not seem to re-render - and useEffect is not called, which is what will update the canvas. You can see I have localPolygon as the second param in useEffect. Any ideas?

CodePudding user response:

I don't know what type local polygon is, but I guess the problem is related to "shallow comparison"

  • Related