How to set some state in render loop?

I have few models in scene and when I have camera(first person perspective) close to any model, I wanna active some state and also wanna know model’s data, so i have that logic in the useFrame hook and I am setting up global state in useFrame too. But that means the components where I am using that state will also rerender in loop whenever I am close to aby model in scene so ofc its not a good practice so What i doing is, I am comapring both state using JSON.stringify(), before setting up the state, it works for the most parts but sometimes it breaks for some reasons and zustand sets the state on every frame of app. So what could be the solution for this?

This is not really a three js concern but more about javascript, sorry about that but will apperciate if someone will help me to solve this problem.

Not setting state on each frame. Also, if I understood correctly the scene you described, you shouldn’t really need a global state either - a container component containing the interactive meshes should be able to handle the state locally:

Container responsibility:

  • Render children meshes
  • Run the onFrame handler that determines the proximity between the camera and children meshes
  • Pass to the children meshes (as props) whether they are close or far away from the camera

Model responsibility:

  • Render the model depending on the props passed from the parent container (no onFrame needed here)
  • If necessary, switch local model state whenever props change (if it’s needed at all)

everything that @mjurczyk said + zustand does not have to update everything reactively. look in the docs for “transient” updates. useFrame is meant for very fast view mutations, you don’t set in there, you don’t await state - you merely have access to state.