refactor(front-end): use ref instead of state to avoid unnecessary rerenders

This commit is contained in:
Josue 2021-07-13 19:55:55 -04:00
parent e3453a1fe6
commit f08b3adc12

View File

@ -1,7 +1,8 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, memo } from 'react';
import { RFB } from 'novnc-node'; import { RFB } from 'novnc-node';
type VncProps = { type VncProps = {
rfb: typeof RFB;
// The URL for the VNC connection: protocol, host, port, and path. // The URL for the VNC connection: protocol, host, port, and path.
url: string; url: string;
@ -38,51 +39,55 @@ type VncProps = {
localCursor?: boolean; localCursor?: boolean;
}; };
const VncDisplay = (props: VncProps): JSX.Element => { const VncDisplay = ({
rfb,
style,
url,
encrypt,
...opts
}: VncProps): JSX.Element => {
const canvasRef = useRef<HTMLCanvasElement>(null); const canvasRef = useRef<HTMLCanvasElement>(null);
const [rfb, setRfb] = useState<typeof RFB>(undefined);
const { style, url, encrypt, ...opts } = props;
/* eslint-disable no-param-reassign */
useEffect(() => { useEffect(() => {
if (!rfb) if (!rfb.current)
setRfb( rfb.current = new RFB({
new RFB({ ...opts,
...opts, style,
encrypt: encrypt !== null ? encrypt : url.startsWith('wss:'), encrypt: encrypt !== null ? encrypt : url.startsWith('wss:'),
target: canvasRef.current, target: canvasRef.current,
}), });
);
if (!rfb) return; if (!rfb.current) return;
if (!canvasRef.current) { if (!canvasRef.current) {
/* eslint-disable consistent-return */ /* eslint-disable consistent-return */
return (): void => { return (): void => {
rfb.disconnect(); rfb.current.disconnect();
setRfb(undefined); rfb.current = undefined;
}; };
} }
rfb.connect(url); rfb.current.connect(url);
return (): void => { return (): void => {
rfb.disconnect(); rfb.current.disconnect();
setRfb(undefined); rfb.current = undefined;
}; };
}, [rfb, encrypt, opts, url]); }, [rfb, encrypt, opts, url, style]);
const handleMouseEnter = () => { const handleMouseEnter = () => {
if (!rfb) return; if (!rfb.current) return;
// document.activeElement && document.activeElement.blur(); if (document.activeElement) (document.activeElement as HTMLElement).blur();
rfb.get_keyboard().grab(); rfb.current.get_keyboard().grab();
rfb.get_mouse().grab(); rfb.current.get_mouse().grab();
}; };
const handleMouseLeave = () => { const handleMouseLeave = () => {
if (!rfb) return; if (!rfb.current) return;
rfb.get_keyboard().ungrab(); rfb.current.get_keyboard().ungrab();
rfb.get_mouse().ungrab(); rfb.current.get_mouse().ungrab();
}; };
return ( return (
@ -112,4 +117,6 @@ VncDisplay.defaultProps = {
shared: false, shared: false,
}; };
export default VncDisplay; const MemoVncDisplay = memo(VncDisplay);
export default MemoVncDisplay;