How to use state management with react-three-fiber without performance issues

This is not really a specific code issue and more of a general question on the tools out there.

I am using react and react-three-fiber, I have recently tried to use state management with Zustand to organize my app and I am representing each of my 3D models in state through their most basic props, and then rendering them from that. Whenever I want to change something about my 3D models, I change the state and the models are updated automatically through hooks like useEffect, that way everything in my app follows a single source of truth. Now I noticed that this process significantly reduces performance; not by a lot, but enough to be noticeable.

Is this a common issue? And if so, what are some tools or workarounds that can help with that? Or is this behavior not expected at all and I should expect something to be wrong with my code?

Thanks!

1 Like

state management won’t affect performance, use whatever you want. fiber itself uses zustand so it would be free in terms of bundle size.

there are two paradigms:

  • app/local state
  • transitionary/frame-by-frame state, which in threejs is your ticker function or render-loop

you do not push frame updates through app/local state, it wold not make sense. the interpolation of state is a components concern. it interpolates with useFrame, which is also where you get deltas, without which you would not be able to make your app refreshrate independent and it would run at varying speeds depending on the monitor.

frame-by-frame state should also watch out that it doesn’t re-create classes, materials, vectors, etc. it just mutates, and interpolates from the current value towards the new goal value (which is app or local state).

pitfalls

scaling-performance

discoverthreejs.com/tips-and-tricks/

PS, if you have performance issues with just app/local state you have a bug, most likely you end up re-creating things that should not be re-created, for instance materials which is very expensive.

2 Likes

btw consider poimandres discord. if you have a threejs issue but you’re using fiber no problem, but for purely or semi react related questions use discord in order to keep this forum more focussed

1 Like