movie-web/src/hooks/useFade.ts

30 lines
763 B
TypeScript
Raw Normal View History

2022-02-13 18:49:03 +01:00
import React, { useEffect, useState } from "react";
2023-01-08 15:42:35 +01:00
import "./useFade.css";
2022-02-13 18:49:03 +01:00
2023-01-08 15:42:35 +01:00
export const useFade = (
initial = false
): [boolean, React.Dispatch<React.SetStateAction<boolean>>, any] => {
2022-02-13 18:49:03 +01:00
const [show, setShow] = useState<boolean>(initial);
const [isVisible, setVisible] = useState<boolean>(show);
// Update visibility when show changes
useEffect(() => {
if (show) setVisible(true);
}, [show]);
// When the animation finishes, set visibility to false
const onAnimationEnd = () => {
if (!show) setVisible(false);
};
const style = { animation: `${show ? "fadeIn" : "fadeOut"} .3s` };
// These props go on the fading DOM element
const fadeProps = {
style,
2023-01-08 15:42:35 +01:00
onAnimationEnd,
2022-02-13 18:49:03 +01:00
};
return [isVisible, setShow, fadeProps];
};