-
-
Notifications
You must be signed in to change notification settings - Fork 854
/
use-motion-ref.ts
41 lines (38 loc) · 1.39 KB
/
use-motion-ref.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import * as React from "react"
import { useCallback } from "react"
import type { VisualElement } from "../../render/VisualElement"
import { isRefObject } from "../../utils/is-ref-object"
import { VisualState } from "./use-visual-state"
/**
* Creates a ref function that, when called, hydrates the provided
* external ref and VisualElement.
*/
export function useMotionRef<Instance, RenderState>(
visualState: VisualState<Instance, RenderState>,
visualElement?: VisualElement<Instance> | null,
externalRef?: React.Ref<Instance>
): React.Ref<Instance> {
return useCallback(
(instance: Instance) => {
instance && visualState.mount && visualState.mount(instance)
if (visualElement) {
instance
? visualElement.mount(instance)
: visualElement.unmount()
}
if (externalRef) {
if (typeof externalRef === "function") {
externalRef(instance)
} else if (isRefObject(externalRef)) {
;(externalRef as any).current = instance
}
}
},
/**
* Only pass a new ref callback to React if we've received a visual element
* factory. Otherwise we'll be mounting/remounting every time externalRef
* or other dependencies change.
*/
[visualElement]
)
}