Animate React Component on Render with Framer Motion

Animations in React that depend on component life cycle can be difficult to get right. Without a user event to drive our animation, you have to have a deep understanding of component life cycle and effects in order to properly trigger animations….or do you?

Framer Motion handles the relationship between animation and life cycle events for you. Let’s animate a React component on render with a transform: scale animation.

Without Framer Motion, your approach may be to apply a transform: scale using the Effect hook and useState like below:

//In our component...
const [rendered, setRendered] = useState(false);


return (
   <div style={{height: 100, rendered? {transform: scaleY(2)}: null}}

Even worse, you may be tempted to put a setTimeout in the useEffect to get the animation to kinda/sorta work. Yuck!

Now take a look at this Code Sandbox: Animate React component on render.

Framer Motion beautifully handles hooking into the proper effects for you, so you can focus on creating the perfect animation. The above animation was accomplished with only these few lines of code:

export const AnimatedAlert = () => (
      initial={{ scale: 0 }}
      animate={{ scale: 1.5 }}
         delay: 0.5,
         duration: 1
      <Alert severity="error">Framer Motion FTW!</Alert>

Framer Motion has an extensive API for animations. It elegantly handles typical animations and also gives you tools such variants to cleanly apply custom animations to different component states. The Framer Motion syntax feels somewhat like having the power of css with the flexibility of writing JavaScript.

Share this post:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.