frontend-interview-questions icon indicating copy to clipboard operation
frontend-interview-questions copied to clipboard

Unexpected behavior without useCallback hook

Open DasAnurag31 opened this issue 1 year ago • 0 comments
trafficstars

if (isMouseDown) { const startBox = selectedBoxes[0]; const endBox = boxNumber;

  const startRow = Math.floor((startBox - 1) / cols);
  const startCol = (startBox - 1) % cols;

  const endRow = Math.floor((endBox - 1) / cols);
  const endCol = (endBox - 1) % cols;

  const minRow = Math.min(startRow, endRow);
  const maxRow = Math.max(startRow, endRow);
  const minCol = Math.min(startCol, endCol);
  const maxCol = Math.max(startCol, endCol);

  const selected = []; // BUG
  const selected = [startBox]; // FIX

  for (let row = minRow; row <= maxRow; row++) {
    for (let col = minCol; col <= maxCol; col++) {
      selected.push(row * cols + col + 1);
    }
  }
  console.log(selected);
  setSelectedBoxes(selected);
}

There is a bug in the code, as we are loosing the initial coordinate of the selected part, when we are re-calculating it. It is avoided when we use the callBack hook because it is not calculated when selected box changes, as we have only given the parameter as mouseDown. 

I thought of opening a PR, but i guess it's too minor of an issue, so i mentioned the fix in the issue itself. 

Great tutorial!

DasAnurag31 avatar Mar 24 '24 14:03 DasAnurag31