-
Hi, 👋 I am recently experimenting a little with the r3f and I can't find an answer to the one question. Long: I'm trying to make a game with keyboard controls and I use react useState hook to manage currently pressed keys and based on that move an Object3D across the Canvas. As I know, the react component state mutation is causing the component to rerender. With that knowledge, I'm trying to wrap my head around the optimal way to manipulate Object3D in r3f. Is rerendering it every time a user press a key a good idea? I also know that I can use Object3D element ref to manipulate it changing its properties directly, but as for now, I couldn't manage to do it with keyboard controls and I'd like to know if it's the way to go. More detailed question: What is the best approach to manipulate Object3D with a keyboard in r3f? I've made a simple repo with a stateless and stateful box console-logging every render to show an issue. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
this one should answer it: https://docs.pmnd.rs/react-three-fiber/advanced/pitfalls the tldr is, flags yes, fast updates no. just like plain react, you would never animate a div across the screen with setState but you can set props on it, colors, text, things that happen occasionally. with zustand you can tie components to state without causing render, useFrame would then write updates to the object3d. this especially makes no sense: const [rotation, setRotation] = useState(0)
useFrame(({ clock }) => setRotation(() => Math.sin(clock.getElapsedTime()))) you are pumping 60 component updates per second through react, 60 times per second where it has to diff for changes, execute all hooks, then render, then render the components children, then render theirs, and so on. essentially you're creating a feedback loop. you probably wouldn't do that with react-dom, here it's the same thing --- don't. 😄 you can choose between:
|
Beta Was this translation helpful? Give feedback.
-
Why even use react then if you end up just mutating state directly like classical imperative programming anyway. |
Beta Was this translation helpful? Give feedback.
this one should answer it: https://docs.pmnd.rs/react-three-fiber/advanced/pitfalls
the tldr is, flags yes, fast updates no. just like plain react, you would never animate a div across the screen with setState but you can set props on it, colors, text, things that happen occasionally.
with zustand you can tie components to state without causing render, useFrame would then write updates to the object3d.
this especially makes no sense:
you are pumping 60 component updates per second through react, 60 times per second where it has to diff for changes, execute all hooks…