Skip to content

🎥 Make videos programmatically with React

`@remotion/three`: use frameloop=demand in rendering to improve render performance

Igor Samokhovetsa1f9021742f4
diff --git a/packages/three/src/ThreeCanvas.tsx b/packages/three/src/ThreeCanvas.tsx
index 9037442460..f9c46e1caf 100644
--- a/packages/three/src/ThreeCanvas.tsx
+++ b/packages/three/src/ThreeCanvas.tsx
@@ -1,7 +1,13 @@
import type {RootState} from '@react-three/fiber';
import {Canvas, useThree} from '@react-three/fiber';
-import React, {useCallback, useLayoutEffect, useState} from 'react';
-import {Internals, continueRender, delayRender} from 'remotion';
+import React, {useCallback, useEffect, useLayoutEffect, useState} from 'react';
+import {
+ Internals,
+ continueRender,
+ delayRender,
+ getRemotionEnvironment,
+ useCurrentFrame,
+} from 'remotion';
import {SuspenseLoader} from './SuspenseLoader';
import {validateDimension} from './validate';
@@ -28,6 +34,23 @@ const Scale = ({
return null;
};
+const FiberFrameInvalidator = () => {
+ const {invalidate} = useThree();
+
+ const frame = useCurrentFrame();
+
+ useEffect(() => {
+ invalidate();
+ }, [frame, invalidate]);
+
+ return null;
+};
+
+const {isRendering} = getRemotionEnvironment();
+
+// https://r3f.docs.pmnd.rs/advanced/scaling-performance#on-demand-rendering
+const shouldUseFrameloopDemand = isRendering;
+
/*
* @description A wrapper for React Three Fiber's <Canvas /> which synchronizes with Remotion's useCurrentFrame().
* @see [Documentation](https://www.remotion.dev/docs/three-canvas)
@@ -57,7 +80,13 @@ export const ThreeCanvas = (props: ThreeCanvasProps) => {
return (
<SuspenseLoader>
- <Canvas style={actualStyle} {...rest} onCreated={remotion_onCreated}>
+ <Canvas
+ style={actualStyle}
+ {...rest}
+ frameloop={shouldUseFrameloopDemand ? 'demand' : 'always'}
+ onCreated={remotion_onCreated}
+ >
+ {shouldUseFrameloopDemand && <FiberFrameInvalidator />}
<Scale width={width} height={height} />
<Internals.RemotionContextProvider contexts={contexts}>
{children}