File size: 574 Bytes
8a29801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import {useEffect, useRef, useState} from "react"

export function useEngineSnapshot<T>(getSnapshot: () => T, subscribe: (onChange: () => void) => () => void): T {
  const getSnapshotRef = useRef(getSnapshot)
  const subscribeRef = useRef(subscribe)
  getSnapshotRef.current = getSnapshot
  subscribeRef.current = subscribe
  const [snapshot, setSnapshot] = useState(() => getSnapshot())

  useEffect(() => {
    setSnapshot(getSnapshotRef.current())
    return subscribeRef.current(() => setSnapshot(getSnapshotRef.current()))
  }, [])

  return snapshot
}