I’m working on a React component that handles animations for a login modal. Currently, I’m using setTimeout in combination with useEffect to delay the activation of animation classes when the modal opens.
The setTimeout introduces a delay to ensure animations trigger correctly when the modal is displayed. However, I feel this approach is not ideal, and I’m wondering if there’s a better or more React-idiomatic way to achieve the same result without relying on setTimeout.
{loginOpen && (
<>
<div
className={`nav-background-fade ${fadeAnimation ? "nav-background-fade-animation" : ""}`}
onClick={(e) => handleCloseLoginBox(e)}
></div>
<div className={`right-side-page ${fadeAnimation ? "right-side-page-animation" : ""}`}>
<h1>Login</h1>
</div>
</>
)}
useEffect(() => {
if (loginOpen) {
const timer = setTimeout(() => {
setfadeAnimation(true);
}, 100);
return () => clearTimeout(timer);
} else {
setfadeAnimation(false);
}
}, [loginOpen]);
.nav-background-fade {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 998;
transition: opacity 1s ease;
opacity: 0;
}
.nav-background-fade-animation {
opacity: 1;
}
.right-side-page {
position: fixed;
top: 0;
right: -20vw;
width: 20vw;
height: 100vh;
background-color: var(--main-white-color);
z-index: 999;
transition: right 0.3s ease;
}
.right-side-page-animation {
right: 0;
}