Appearance
useTransition
Transition between values
Demo
Usage
Define a source value to follow, and when changed the output will transition to the new value. If the source changes while a transition is in progress, a new transition will begin from where the previous one was interrupted.
tsx
import { TransitionPresets, useTransition } from '@reause/core'
import { useState } from 'react'
const [source, setSource] = useState(0)
const output = useTransition(source, {
duration: 1000,
easing: TransitionPresets.easeInOutCubic,
})
// each `setSource(next)` tweens `output` from its current value to `next`
setSource(100)Transition easing can be customized using cubic bezier curves.
tsx
useTransition(source, {
easing: [0.75, 0, 0.25, 1],
})The following transitions are available via the TransitionPresets constant.
lineareaseInSineeaseOutSineeaseInOutSineeaseInQuadeaseOutQuadeaseInOutQuadeaseInCubiceaseOutCubiceaseInOutCubiceaseInQuarteaseOutQuarteaseInOutQuarteaseInQuinteaseOutQuinteaseInOutQuinteaseInExpoeaseOutExpoeaseInOutExpoeaseInCirceaseOutCirceaseInOutCirceaseInBackeaseOutBackeaseInOutBack
For more complex easing, a custom function can be provided.
tsx
function easeOutElastic(n) {
return n === 0
? 0
: n === 1
? 1
: (2 ** (-10 * n)) * Math.sin((n * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1
}
useTransition(source, {
easing: easeOutElastic,
})To control when a transition starts, set a delay value. To choreograph behavior around a transition, define onStarted or onFinished callbacks.
tsx
const output = useTransition(source, {
delay: 1000,
onStarted() {
// called after the transition starts
},
onFinished() {
// called after the transition ends
},
})To stop transitioning, define a boolean disabled property. Be aware, this is not the same a duration of 0. Disabled transitions track the source value synchronously. They do not respect a delay, and do not fire onStarted or onFinished callbacks.
Type Declarations
ts
export type CubicBezierPoints = [
number,
number,
number,
number
]
export type EasingFunction = (n: number) => number
export interface UseTransitionOptions {
abort?: () => boolean;
delay?: number;
disabled?: boolean;
duration?: number;
easing?: EasingFunction | CubicBezierPoints;
window?: Window;
onFinished?: () => void;
onStarted?: () => void;
}
export const TransitionPresets
export function useTransition(source: number, options?: UseTransitionOptions): number
export function useTransition(source: readonly number[], options?: UseTransitionOptions): number[]