Hooks
useSettings

useSettings

With this hook you can save the settings you want without exposing them to the user. It is useful for example to save and restore the position of the camera.

Example of use.

import { useRef, useEffect, useCallback } from 'react'
import { OrbitControls, PerspectiveCamera } from '@react-three/drei'
import { useThree } from '@react-three/fiber'
import { useDefaultCamera, useSettings } from './effect-control'
 
export default function App() {
  const cameraRef = useRef()
  const { setDefaultCamera } = useDefaultCamera()
 
  // Create a new settings object
  const cameraSettings = useSettings('camera', {
    orbitTarget: { x: 0, y: 0, z: 0 },
    position: { x: 0, y: 0, z: 50 },
    // Be aware that some classes might return a different object
    // than the one you expect when it's stringified
    // Example: Euler class used in rotation in three.js
    // returns _x, _y, _z instead of x, y, z
    rotation: { _x: 0, _y: 0, _z: 0 },
  })
 
  // Set the new default camera
  const handleCameraRef = useCallback((node) => {
    setDefaultCamera(node)
    cameraRef.current = node
  }, [])
 
  // Set the orbit target that was saved
  const handleOrbitRef = useCallback((node) => {
    if (!node) return
    node.target.x = orbitTarget.x
    node.target.y = orbitTarget.y
    node.target.z = orbitTarget.z
  }, [])
 
  function onControlEnd(event) {
    // Each time the camera is moved, update the settings
    cameraSettings.update({
      orbitTarget: event.target.target,
      position: cameraRef.current.position,
      rotation: cameraRef.current.rotation,
    })
  }
 
  return (
    <>
      <PerspectiveCamera
        ref={handleCameraRef}
        makeDefault
        // Set the camera position that was saved
        position={[position.x, position.y, position.z]}
        rotation={[rotation._x, rotation._y, rotation._z]}
      />
      <OrbitControls
        ref={handleOrbitRef}
        onEnd={onControlEnd}
      />
    </>
  )
}