useRef
Storing non-reactive values
// a small hook to contain interval logic which can be canceled
function usePulse({ interval, callback }) {
// create a ref
const timer = useRef(null);
// timer.current will contain our value over time and will always
// refer to the latest value
const cancel = useCallback(() => clearInterval(timer.current));
useEffect(() => {
// update the value with the new interval
timer.current = setInterval(callback, interval);
return cancel;
}, [interval, callback]);
// and return a function to cancel it
return cancel;
}
function usePulseButton() {
const [shouldPulseIn, setPulseIn, isPulseIn] = useAtom(true);
// on each interval tick, we'll flip the pulse value
// that'd then trigger a CSS class change to do an animation
const cancelPulse = usePulse(1000, useCallback(() => {
setPulseIn(!shouldPulseIn());
}));
const buttonRef = useCallback(element => {
return fromEvent(element, 'click').subscribe(event => {
// when the value is clicked we'll stop the animation
// using the callback
cancelPulse();
});
});
return {
buttonRef,
isPulseIn
};
}Storing all referenced elements
Easy access to just a single referenced element
Last updated
Was this helpful?