#React native game pad update#
For example, the "Press Start" screen should only update state when the "start button" is changed. Ideally, you should only track what buttons you need for the component. To reduce this, I tried implementing a check before updating the controller input. This became clear when I ran a console.log inside the component and it crashed the browser every time. To handle things like controller input across components, I would use the hook to grab gamepad input, and shove it all into the component state.
#React native game pad code#
You can compare the context's source code in the repo to the context example above and see the difference. Once I put my code into a proper linting environment with Typescript, I started to get errors from not using (and misusing) performance optimization techniques like React's useCallback and useMemo. Then when updating the state, instead I updated the ref ( gamepad.current = newInput). So instead of useState, I ran useRef to create a new "ref". Instead of using React's state, I used "refs". This meant that every time the requestAnimationFrame ran, it was updating the component state, and causing a re-render. The first mistake I made was using React state to store the gamepad input. Also doesn't run without hardware acceleration in Chrome (which uses GPU) - meaning it was intense. Works great on my gaming PC, but had major performance issues when moving to Macbook laptop with internal GPU. If you have a small app or segment of the app that needs gamepad data, the context is better. Or if you have an app with many elements and game elements aren't nested together, or in a close enough parent. If you have a single component that needs to be aware of the gamepad, the hook is ideal. You have to weigh this performance cost versus the alternative of holding it in context provider higher in the render tree, which re-renders all children on each change. This means that multiple components will have the state (or ref) of the entire gamepad state - updated constantly.