In this video, we show developing a game with Phaser and using React for the user interface. Using React to alleviate the burden of handling the UI in Canvas. RequestAnimationFrame can be expensive and should be used for the game only. The canvas game shouldn't be wasting valuable updates for the UI.
The game is a NextJS application that from there, it builds the Phaser game and game starts up normally. However, the Nextjs application is handling the UI elements like in the video: merchant dialog, player bag, player armory, and other dialogs like the death dialog.
For the bridge to work between Phaser and React, I'm using addEventListener on the document object to send objects back and forth. The implementation of addEventListener is contained within a hook that implements useEffect so that state can be passed in.
The performance issue that was solved here was to convert the class components (Bag, Armory, DeathDialog, MerchantDialog) to functional components and then use hooks to manage the add/remove listeners.
Take the time to learn hooks and using functional components.
Only call Hooks at the top level. Don't call Hooks inside loops, conditions, or nested functions.
If you are using class components, do not worry - porting class components to functional components most of the time, is trivial.
Pay close attention to useState when rewriting your new functional components. Once you spend time writing functional components, I find you'll really enjoy using them and paired with hooks makes the component design simple to implement and iterate on the design of the interface.
Below is a bare bones example of a using a Hook and implementing useEffect to attach events with addEventListener.
Taking the time to understand hooks and why we are using them is the first important building block to building the bridge between the game engine and UI. Pick the areas that you need side effects - the Effect Hook, which allows for data fetching, DOM updates, and for our example for the bridge: we use addEventListener within useEffect.
Here's all the resources and frameworks used in the video.