Skip to content

Instantly share code, notes, and snippets.

@seantai
Created March 8, 2024 00:11
Show Gist options
  • Save seantai/550820736b7fb546484c8160b12b7b1c to your computer and use it in GitHub Desktop.
Save seantai/550820736b7fb546484c8160b12b7b1c to your computer and use it in GitHub Desktop.
update zustand state in useFrame
import { useFrame } from '@react-three/fiber'
import React, { useEffect, useRef } from 'react'
import { create } from 'zustand'
function AnimateBoxWithZustand() {
const useStore = create((set) => ({
position: [0, 0, 0],
setPosition: (newPosition) => set(() => ({ position: newPosition })),
updatePosition: (time) =>
set((state) => ({
position: [state.position[0], state.position[1] + Math.sin(time) * 0.001, state.position[2]]
}))
}))
const positionRef = useRef(useStore.getState().position)
const meshRef = useRef()
useEffect(() => {
const unsubscribe = useStore.subscribe((state) => {
positionRef.current = state.position
})
return () => {
unsubscribe()
}
}, [])
useFrame(({ clock }) => {
const elapsedTime = clock.getElapsedTime()
// console.log('posBefore', positionRef.current)
useStore.getState().updatePosition(elapsedTime)
// console.log('posAfter', positionRef.current)
if (meshRef.current) {
meshRef.current.position.set(...positionRef.current)
}
})
return (
<mesh ref={meshRef}>
<boxGeometry />
<meshMatcapMaterial />
</mesh>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment