Imperatives & Refs
While this section uses examples using hooks
using createRef
inside a class component will give you the same result.
Imperative API
a.k.a Why did you get rid of
set
?
The old api looked something like this:
const [props, set, stop] = useSpring(() => ({ opacity: 1 }))
// Update spring with new props
set({ opacity: toggle ? 1 : 0 })
And while this was really good, it's not the best API, having the imperative API returned from the spring stops you from digging for the correct function. It makes extensibility easier too if we add more api methods.
However, if you're really set on loving the old set
, from 9.1.0
we have aliased the second arg to call api.start
which is the v9 equivalent of set
. This will give you a depreciation notice:
The from
prop
The from
prop now behaves differently in imperative updates. When defined, it implies the reset
prop is true. Previously, the from
prop would not affect the animation unless reset: true
was explicitly defined.
To prevent this behavior, you can define reset: false
.
const { x } = useSpring({ x: 0 })
useEffect(() => {
// This animates as expected, from 100 to 0.
x.start({ from: 100, to: 0 })
})
API methods
The api object, set to a SpringRef or returned as the second arg of an array returned from a spring has the following methods:
const api = {
// start your animation optionally giving new props to merge e.g. a `to` object
start: (props) => AnimationResult,
// sets the spring to specific passed values
set: (props) => void,
// Add props to each controller's update queue.
update: (props) => this,
// Add a controller to the springRef
add: (ctrl) => this,
// Delete a controller from the springRef
delete: (ctrl) => this,
// Cancel some or all animations depending on the keys passed, no keys will cancel all.
stop: (cancel, keys) => this,
// pause specific spring keys of the spring function
pause: (keys) => this
// resume specific spring keys of the spring function
resume: (keys) => this
}
Using Refs
Introducing useSpringRef
! The library version of useRef
to be used instead of useRef
in the following situations:
const springRef = useSpringRef()
const { size, ...rest } = useSpring({
ref: springApi,
config: config.stiff,
from: { size: '20%', background: 'hotpink' },
to: {
size: '100%',
background: 'white',
},
})
useEffect(() => {
// this will give you access to the same API documented above
console.log(springRef.current)
}, [])
Internally, the ref has the Controller
added to it using the add
method. Therefore, using useRef
will throw an error.
This is especially helpful when using useChain
.