What this isn't:
You'll get the most out of this talk if you:
Get the source code
For when you need to move data from the backend to the frontend with no latency
credit: Marshall Ruse
react-use-websocket
react-use-websocket-lite
requestAnimationFrame?
setInterval(()=>draw(),1000/60)
requestAnimationFrame(draw)
function draw() {
//animation logic goes here
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
useEffect(() => {
let animationFrameId;
const draw = () => {
//animation logic here
animationFrameId = requestAnimationFrame(draw);
};
draw();
return () => {
cancelAnimationFrame(animationFrameId);
};
},[]);
render
render
<canvas> element alsoconst Canvas = ({props})=>{
const canvasRef = useRef(null);
const [context, setContext] = useState(null);
useEffect(() => {
if (canvasRef.current) {
setContext(canvasRef.current.getContext("2d"));
}
}, []);
return <canvas ref={canvasRef}>;
}
const listOfPoints=[{x:0,y:0},{x:2,y:5}....]
context.clearRect(0, 0, canvasWidth, canvasHeight);
context.beginPath();
context.moveTo(startX,startY);
for (const pointPair of listOfPoints) {
context.moveTo(
pointPair.x
pointPair.y);
}
context.stroke();
const myPoints = [{x:10,y:220},{x:125,y:10},{x:250,y:220}];
ctx.strokeStyle="lightblue";
ctx.beginPath();
ctx.moveTo(250,220);
for (const point of myPoints){
ctx.lineTo(point.x,point.y);
}
ctx.stroke();const canv = //same stuff as before
let animationFrameId;
const draw = ()=>{
ctx.clearRect(0,0,300,300);
const myPoints = //determined by backend, or (in this example case, Math.random())
ctx.beginPath();
for (const point of myPoints){
ctx.lineTo(point.x,point.y);
}
ctx.stroke();
animationFrameId = requestAnimationFrame(draw);
}
useEffect(() => {
const draw = () => {
if (facesRef.current) {
context.clearRect(0, 0, canvasWidth, canvasHeight);
context.beginPath();
for (const face_point of facesRef.current) {
context.lineTo(
face_point.x,
face_point.y,
);
context.stroke();
}
}
}
};
let animationFrameId;
const renderAndRequestNewFrame = () => {
draw();
sendMessage("{'sendNext':'frame'}");
animationFrameId = requestAnimationFrame(renderAndRequestNewFrame);
};
renderAndRequestNewFrame();
return () => {
cancelAnimationFrame(animationFrameId);
}, [facesRef, context, sendMessage]);
componentShouldUpdate in the days of class componentsconst MyComponent = ({props})=>{
/*some very cool stuff here*/
return (<>Very Cool Component {props.name}<>)
}
export default React.memo(MyComponent);
myArray.forEach(item=>doSomethingWith(item));
//is SIGNIFICANTLY slower than
for (const item of myArray){
doSomethingWith(item)
}
Some benchmarks put for..of as more than twice as fast as .forEach.
(I tried my own benchmark and forEach crashed my computer 🤷♀️)
.time() and .timeEnd()console.time("my expensive operation")
//do something expensive
console.timeEnd("my expensive operation")
produces...
my expensive operation: 15801ms - timer ended
Contact me

Download slides/source code
