Solved: React Hook useEffect - problems re-rendering / resetting

263 Views Asked by At

I am trying to create a reset button, which changes the value of a dependency in a useEffect. I thought this would re-render the component, and thus set all the values to the default values as shown in the code.

 const TransformedDoor = ({ doorHook }) => {
  const { selectedDoor } = doorHook;
  const [ doorWidth, setDoorWidth ] = useState(0);
  const [ doorHeight, setDoorHeight] = useState(0);
  const [ reset, doReset ] = useState(0);

  const DEFAULT_MATRIX = [1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0];
  const [ transformationMatrix, setTransformationMatrix] = useState(DEFAULT_MATRIX);
  const [ doorOffset, setDoorOffset ] = useState({x: 300,y: 200});
  const [ mouseState, setMouseState ] = useState({targetCircle: -1});
  const [ corners, setCorners ] = useState(
    {
     0: {x: 0, y: 0},
     1: {x: doorWidth, y: 0},
     2: {x: doorWidth, y: doorHeight},
     3: {x: 0, y: doorHeight},
    }
  );

  useEffect(() => {
    const { width, height } = selectedDoor;
    const scaler = 200 / Math.max(width, height);
    const w = width * scaler;
    const h = height * scaler;
    if (w !== doorWidth || h !== doorHeight) {
      setDoorWidth(w);
      setDoorHeight(h);
      setCorners({
        0: {x: 0, y: 0},
        1: {x: w, y: 0},
        2: {x: w, y: h},
        3: {x: 0, y: h},
      });
      setTransformationMatrix(DEFAULT_MATRIX);
    }
    console.log(reset + "reset")
  }, [selectedDoor, reset]);

This is the hook that I am updating:

const [ reset, doReset ] = useState(0);

This is the button that does the value change in the dependency of the useEffect. It changes the value of [reset]

<button
   onClick={() => {
     doReset(prev => prev + Math.random());
    }}> Reset </button>

Edit: Solved it!

I edited the if-statement to listen for new reset-values, which triggered the desired actions.

 useEffect(() => {
    const { width, height } = selectedDoor;
    const scaler = 200 / Math.max(width, height);
    const w = width * scaler;
    const h = height * scaler;
    if (w !== doorWidth || h !== doorHeight || reset !== 0) {
      setDoorWidth(w);
      setDoorHeight(h);
      setCorners({
        0: {x: 0, y: 0},
        1: {x: w, y: 0},
        2: {x: w, y: h},
        3: {x: 0, y: h},
      });
      setTransformationMatrix(DEFAULT_MATRIX);
      setReset(0);
    }
    console.log(reset + "reset")
  }, [selectedDoor, reset]);
1

There are 1 best solutions below

1
On

Try renaming doReset to setReset as the documentation proposes here