Breaking down long useEffects - Technoculture/VVplus GitHub Wiki

Creation of a Babylon.js engine

  • Canvas - The CanvasAPI where the Babylon.js engine lies. Here the content is displayed.
  • Engine - The Babylon.js Engine is created on the top of the Canvas. A canvas can hold multiple engines.
  • Scene - Created on the top of the Babylon.js engine, an engine can support multiple scenes too, but switching around can make the code bulky and slow. A scene requires the following elements:
    • Camera - To view the models and the scene
    • Light - A light source is always required to view meshes and models
    • Skybox(optional) - Provides a box to wrap the models in, provides a background as needed.
    • Ground(optional) - A ground like surface to place the models on.
    • Models - The objects that we need to view

Initially, all the components of the Engine were wrapped up in a singular useEffect whose work was to stop infinite re-renderings of the scene and hence stop the page from crashing, however, with addition of features, the code has become very long and bulky and needs to be broken down into several functionalities which creates each component on it's own and links them to the scene seperately.

The code however might keep re-rendering if not used in a useEffect hook and hence the scene needs to be created inside the useEffect hook.

Procedures to break the code into shorter, compact sections:

  1. Develop custom hook for the scene and pass it to custom hooks of other elements to and link them to each other.

Why not follow the above approach?

 const [sceneModel, setScene] = useState<Scene>();
  useEffect(() => {
    const canvas = canvasRef.current;
    const engine = new Engine(canvas, true);
    const scene = new Scene(engine);
    const light = new HemisphericLight("light", new Vector3(-1, 1, -1), scene);
    light.intensity = 0.7;
    engine.runRenderLoop(function () {
      scene.render();
    });
    window.addEventListener("resize", function () {
      engine.resize();
    });
    setScene(scene);
  }, [canvasRef]);
  return sceneModel as Scene;
}
  • Creates a scene object which has type of either Babylon Scene or null, which causes several errors while linking the scene with camera and light.
  • Custom hooks are unusable in useEffect hook which wraps the engine and scene.
  1. Creating functions instead of hooks and export them to be used instead of hooks.

Disadvantages of this method

  • They might cause type errors if not assigned types properly

Advantages:

  • Can be used inside hooks
  • This method doesn't create the scene using a custom hook
  • We can add other elements only when the scene is ready

Materials for reference:

⚠️ **GitHub.com Fallback** ⚠️