Skip to content

Commit 643b4a9

Browse files
authored
docs: Describe combining ref forwarding with animated (#1734)
1 parent c4c7de9 commit 643b4a9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

docs/src/pages/basics.mdx

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,3 +380,48 @@ useEffect(() => {
380380
api.start({ x: 100, y: 100 })
381381
}, [])
382382
```
383+
384+
### Forwarding refs and the `animated` HoC
385+
386+
For performance reasons, the attributes of animated DOM elements are updated directly by `animated` using a ref to the DOM node, rather than via React updates. Internally, `animated` figures out the difference between DOM elements and regular components by checking the type of the component using a `ref`. This means that if you use `forwardRef` on a component wrapped with `animated` and then pass that ref onto a DOM node, `animated` will treat that component as though it were a DOM node itself, and will stop triggering React updates to interpolate when the animated props change.
387+
388+
For example:
389+
390+
```jsx
391+
const MyAnimatedComponent = animated(({ value }) => (
392+
<div>{value}</div>
393+
))
394+
395+
const MyAnimatedComponentWithRefForwarding = animated(forwardRef(({ value }, ref) => (
396+
<div ref={ref}>{value}</div>
397+
)))
398+
399+
const MyComponentWithSpring = () => {
400+
const { value } = useSpring({
401+
from: { value: 0 },
402+
to: { value: 1 },
403+
});
404+
405+
return (
406+
<>
407+
/* This component will automatically update as "value" changes */
408+
<MyAnimatedComponent value={value} />
409+
410+
/* This component will not automatically update as "value" changes */
411+
<MyAnimatedComponentWithRefForwarding value={value} />
412+
</>
413+
);
414+
}
415+
```
416+
417+
You can work around this problem by forwarding refs as regular props:
418+
419+
```jsx
420+
const AnimatedComponent = animated(({ value, forwardedRef }) => (
421+
<div ref={forwardedRef}>{value}</div>
422+
))
423+
424+
const AnimatedComponentWithRefForwarding = useRef((props, ref) => (
425+
<AnimatedComponent {...props} forwardedRef={ref} />
426+
))
427+
```

0 commit comments

Comments
 (0)