Hooks 4: useRef


useRef

I often use this hook to detect the change of size of the canvas or div.


const targetRef = useRef();
const updateOffset = () =>{
    if (targetRef.current){
        setDims({width:targetRef.current.offsetWidth,
            height:targetRef.current.offsetHeight});
    }
}
return (
    <>
    <canvas id="canvas"
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleMouseUp}
        className={classes.canvas}
        width={imgW} height={imgH}
        ref={targetRef}
    />
    </>

)
    

References