Zooming in React ThreeJS scene with zoombar and wheel scroll

Viewed 116

I am designing a 3D scene by react-three fiber, and I want to be able to zoom in on the scene via multiple sources (I'm using a zoom Bar and mouse wheel scrolling for zooming now, but other sources may be added in the future like buttons for zoom in and out). To do so, I am using a global state ZoomAmount variable which is a DOM element, and in the onchange callback of the bar, this variable is changed:

const handleChange = () => {
    setZoomAmount(refZoomBar.current.value)
}

then I made a hook for zoomAmount state using the react useEffect, so I can change camera.position.z (changing this makes zoom effect)

useEffect(() => {
    camera.position.z = ZoomAmount
}, [ZoomAmount])

The problem is that I want the value of the zoombar to change when I zoom in and out using another input (in this case the mouse wheel scroll,) but when I try to implement this feature in the same way by using hooks, the code enters a loop since these elements are both affected by the same value.

How can I do this without facing this issue?

I have put a running demo of my problem here: https://codesandbox.io/s/zooming-using-multiple-inputs-lub391

I wasn't able to fix this issue but here is what I have tried: I implemented two hooks First, a controls eventlistener to set the ZoomAmount whenever camera changed and second, a hook for zoombar to listen to ZoomAmount value change

controls.current?.addEventListener('change', () => {
      ZoomAmount = camera.position.z
    })
useEffect(()=>{
refZoomBar.current.value = ZoomAmount
},[ZoomAmount])
  • the above codes are not included in the Sandbox code since they make the program misbehave

This is where the infinite loop starts since ZoomAmount gets changed if the value of camera.position.z is changed and then camera.position.z gets changed again because it is hooked to ZoomAmount.

I also tried using two different states for ZoomAmount but it only makes the loop bigger

0 Answers
Related