Hey guys,
I want to access a variables value (that exists in the scene) from a React front end. In the past, I have always just dispatched an event, as Ive only ever needed to do this at particular moments as opposed to regularly every frame (or near enough every frame). What is the best way to access a value from the scene regularly without triggering endless re-renders on the front end?
Im aware that I can dispatch an event, make a variable static and then access it, and add a listener to listen for an event. Any advice on the “correct”, most performant way to approach this is appreciated.
To access a regularly updating variable from the scene in a performant way without triggering endless re-renders in a React frontend, you can consider the following approach:
Use a Custom Hook: Create a custom React hook to encapsulate the logic of subscribing to the variable. This way, React will only trigger a re-render when necessary.
useRef for Scene Variable: Use the useRef hook to hold the reference to your variable in the React component. This way, you can avoid unnecessary re-renders since useRef doesn’t trigger a component re-render on value change.
requestAnimationFrame: Utilize requestAnimationFrame to regularly update the state only when the scene variable changes. This allows you to sync the updates every frame without causing re-renders unless necessary.
useSceneVariable is a custom hook that checks the scene variable’s value each frame.
It updates the React state only if the variable has changed, preventing unnecessary re-renders.
Using requestAnimationFrame ensures that updates are in sync with the browser’s painting cycle.
Feel free to adjust your scene variable retrieval method as necessary. For a more specific implementation, let me know how you’re currently accessing the scene variable or if there are any additional details you’d like to provide!
1 replies left - Get a PRO license for more AI replies. thread_mJy9R8ocZ9QDIP3fnS8dohD2 Reply to this message to continue the conversation
Hey, what the bot said is a feasible approach, but not really efficient (as updates still happen every frame).
If you have multiple pieces of state, and want bi-directional updates (react state can be updated from Needle components, Needle components can subscribe to react state updates), another react-ish way would be that you wrap your react component and the other places that need access to your changing state in a context provider (createContext / useContext). Let me know if you need an example for that.
Hey Herbst,
Ive been using the useContext approach mostly up until now so no need for a sample. I was mostly just looking for validation that this is the recommended approach as I had not had a need to so regularly poll information before.
P.S I definitely didnt trust the bot on this occasion.