Skip to content

Instantly share code, notes, and snippets.

@click2install
Last active August 12, 2021 08:25
Show Gist options
  • Save click2install/f3637f2c5be59844e31c32b795e246aa to your computer and use it in GitHub Desktop.
Save click2install/f3637f2c5be59844e31c32b795e246aa to your computer and use it in GitHub Desktop.
[useFadeOut] - ReactJS hook to fadeOut an element using the opacity and display styles.
import {useLayoutEffect, useRef} from "react";
export default function useFadeOut(ref, fadeTime, visible)
{
const timerId = useRef();
useLayoutEffect(() =>
{
clearTimeout(timerId.current);
if (ref.current)
{
ref.current.style.opacity = visible ? 1 : 0;
ref.current.style.transition = `opacity ${fadeTime}ms ease-in-out`;
if (visible)
{
ref.current.style.display = "block";
}
else
{
timerId.current = setTimeout(() => {ref.current.style.display = "none";}, fadeTime);
}
}
}, [ref, visible, fadeTime]);
}
// usage
//
const loaderRef = useRef(); // the ref to the element to be transitioned
useFadeOut(loaderRef, 500, visible); // 500ms transition time, `visible` state variable to trigger the transition
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment