I have the component with a useState hook into which I pass the SelectionArea class. I did this to improve code readability and usability. Is this bad practice? How does this affect performance?
Component code:
const [selectionArea, setSelectionArea] = useState<SelectionArea | null>(null);
if (selectionArea === null) {
setSelectionArea(new SelectionArea({
offsetX : event.nativeEvent.offsetX,
offsetY : event.nativeEvent.offsetY
}));
} else {
setSelectionArea(new SelectionArea({
offsetX : selectionArea.getOffsetX(),
offsetY : selectionArea.getOffsetY(),
width : event.nativeEvent.offsetX - selectionArea.getOffsetX(),
height : event.nativeEvent.offsetY - selectionArea.getOffsetY()
}));
}
SelectionArea.ts:
class SelectionArea
{
private readonly offsetX : number;
private readonly offsetY : number;
private readonly width : number;
private readonly height : number;
public constructor(options?: ISelectionArea)
{
this.offsetX = options?.offsetX || 0;
this.offsetY = options?.offsetY || 0;
this.width = options?.width || 0;
this.height = options?.height || 0;
}
public getWidth(): number
{
return this.width;
}
public getHeight(): number
{
return this.height;
}
public getOffsetX(): number
{
return this.offsetX;
}
public getOffsetY(): number
{
return this.offsetY;
}
}
export default SelectionArea;
It's not bad practice per se, you'll just have to make sure you don't ever internally mutate the instance (because React won't notice that and won't rerender the component).
However, seeing as you're already using TypeScript, it might be a better idea to just use a SelectionArea
interface, and if you'd need additional functions you'd regularly have on classes, you can model them as free functions á la function getLowerCorner(sa: SelectionArea): [number, number]
.