Transitions
The useBeforeClose
hook enables smooth exit animations by intercepting the close process.
[]
How it works
When a modal is closed, useBeforeClose
intercepts the close call and triggers a two-phase process:
- Animation phase: Sets visibility to
false
, triggering exit animations - Final close: After animation completes, calls
close()
again to unmount
Implementation
The example below uses Motion to manage the animation, but you can use any library you want.
import { useBeforeClose } from "react-easy-modals";
import { AnimatePresence, motion } from "motion/react";
function Modal({ close, isOpen }: ModalProps) {
const [isVisible, setIsVisible] = useState(isOpen);
const canClose = useRef(false);
useBeforeClose(() => {
setIsVisible(false); // Trigger exit animation
return canClose.current; // Prevent immediate close
});
return (
<AnimatePresence
mode="wait"
onExitComplete={() => {
canClose.current = true;
close(); // Final close after animation
}}
>
{isVisible && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
{/* Modal content */}
</motion.div>
)}
</AnimatePresence>
);
}
Key Points
useBeforeClose
should returnfalse
initially to prevent immediate unmounting- Use
isVisible
state to control animation triggers onExitComplete
setscanClose.current = true
and callsclose()
again- The second
close()
call succeeds becausecanClose.current
is nowtrue
Last updated on