Skip to Main Content

Animating with useEffect in React

A selection of animated shapes with motion-blur to symbolize Animations in React using useEffect.

Animations can breathe life into your React applications, making them more interactive and user-friendly. With the introduction of hooks in React, creating animations has become even more intuitive. In this post, we'll explore how to kickstart animations using the useEffect hook.

Why Animate with useEffect?

The useEffect hook in React allows us to perform side effects in function components. This can be anything from data fetching to manually changing the DOM, and yes, starting animations. By using useEffect, we can ensure that our animations start as soon as our component is rendered, providing a smooth user experience.

Setting the Stage for Animation

Before diving into the animation, let's set up our animated view. We'll be animating the opacity of a view, making it fade in smoothly.

const opacity = new Animated.Value(0) 
const opacityListener = result => { 
  const { value } = result 
  if (value === 1) { 
    // Do something once animation ends
    opacity.removeAllListeners() 
  } 
} 

return ( 
  <Animated.View 
    style={{ 
      opacity: opacity, 
    }} 
  > 
    <ThingToAnimate />
  </Animated.View> 
)

In the code above, we've initialized our animated value, opacity to 0. We've also set up a listener that will remove all listeners once our animation reaches its end value of 1.

Kickstarting the Animation with useEffect

Now, let's harness the power of useEffect to initiate our animation:

useEffect(() => {
  opacity.addListener(opacityListener);
  Animated.timing(
    opacity, 
    {
      toValue: 1, 
      duration: 1000,
    },
  ).start();
}, []);

Here, we're adding our previously defined listener to the opacity value. We then use Animated.timing to animate our opacity from its initial value of 0 to its final value of 1 over a duration of 1000 milliseconds (1 second). The start() method is then called to initiate the animation.

Conclusion

With just a few lines of code, we've created a smooth fade-in animation that triggers as soon as our component loads. This approach not only enhances the user experience but also showcases the power and flexibility of React hooks.

For more in-depth details on animations in React Native, check out the official documentation: React Native Animated.

And if you're new to React hooks, we recommend reading Introducing Hooks to get a comprehensive understanding. Happy animating!

Related Posts