|
1 | 1 | import * as React from 'react'; |
2 | 2 | import { interpolateString } from '@mui/x-charts-vendor/d3-interpolate'; |
3 | | -import { useSpring, to } from '@react-spring/web'; |
| 3 | +import { useSpring } from '@react-spring/web'; |
4 | 4 |
|
5 | 5 | function usePrevious<T>(value: T) { |
6 | | - const ref = React.useRef<T | null>(null); |
7 | | - React.useEffect(() => { |
8 | | - ref.current = value; |
9 | | - }, [value]); |
| 6 | + const ref = React.useRef<{ currentPath: T; previousPath?: T }>({ |
| 7 | + currentPath: value, |
| 8 | + previousPath: undefined, |
| 9 | + }); |
| 10 | + if (ref.current.currentPath !== value) { |
| 11 | + ref.current = { |
| 12 | + currentPath: value, |
| 13 | + previousPath: ref.current.currentPath, |
| 14 | + }; |
| 15 | + } |
| 16 | + |
10 | 17 | return ref.current; |
11 | 18 | } |
12 | 19 |
|
13 | | -// Taken from Nivo |
14 | 20 | export const useAnimatedPath = (path: string, skipAnimation?: boolean) => { |
15 | | - const previousPath = usePrevious(path); |
| 21 | + const memoryRef = usePrevious(path); |
| 22 | + |
16 | 23 | const interpolator = React.useMemo( |
17 | | - () => (previousPath ? interpolateString(previousPath, path) : () => path), |
18 | | - [previousPath, path], |
| 24 | + () => |
| 25 | + memoryRef.previousPath |
| 26 | + ? interpolateString(memoryRef.previousPath, memoryRef.currentPath) |
| 27 | + : () => memoryRef.currentPath, |
| 28 | + [memoryRef.currentPath, memoryRef.previousPath], |
19 | 29 | ); |
20 | 30 |
|
21 | | - const { value } = useSpring({ |
22 | | - from: { value: 0 }, |
23 | | - to: { value: 1 }, |
24 | | - reset: true, |
25 | | - immediate: skipAnimation, |
26 | | - }); |
| 31 | + const [{ value }] = useSpring( |
| 32 | + { |
| 33 | + from: { value: 0 }, |
| 34 | + to: { value: 1 }, |
| 35 | + reset: true, |
| 36 | + immediate: skipAnimation, |
| 37 | + }, |
| 38 | + [memoryRef.currentPath], |
| 39 | + ); |
27 | 40 |
|
28 | | - return to([value], interpolator); |
| 41 | + return value.to(interpolator); |
29 | 42 | }; |
0 commit comments