How to use Framer Motion in React
Framer Motion is the most powerful animation library for React, providing declarative animations, gestures, and complex transitions with minimal code. With over 25 years of experience in software development and as the creator of CoreUI, I’ve used Framer Motion extensively for creating sophisticated UI animations. The most effective approach is using the motion components with simple props to define animations declaratively. This provides smooth, performant animations with built-in gesture support and layout animations.
Use motion components with initial, animate, and exit props to create declarative animations in React.
import { motion } from 'framer-motion'
import { useState } from 'react'
function AnimatedCard() {
const [isVisible, setIsVisible] = useState(false)
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>
Toggle Card
</button>
{isVisible && (
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.8 }}
transition={{ duration: 0.3 }}
className="card"
>
<h3>Animated Card</h3>
<p>This card animates smoothly on mount and unmount</p>
</motion.div>
)}
</div>
)
}
This example demonstrates Framer Motion’s declarative approach where you define the initial state, target animation state, and exit animation using props. The motion.div component automatically interpolates between these states when the component mounts, updates, or unmounts. The transition prop controls the animation timing and easing.
Best Practice Note:
This is the same animation approach we use in CoreUI Pro components for smooth, professional interactions. Always wrap conditional renders with AnimatePresence for proper exit animations and use transform properties like scale and translate for better performance.



