An Overview of Animations In React Native

Posted By : Manglesh Tiwari | 14-Aug-2022

mobile application React Native UI

Loading...

Let's talk about animations in react native applications. Clearly, animations make our app look much more attractive and user-friendly, but when implementing animation, we tend to make various mistakes. Let’s learn more about it.

There are two main threads in React native apps-

JavaScript thread and UI thread. if we use state of component and lifeCycle methods to animate a component then this is handled by the JavaScript thread, which causes performance issues and is not recommended at all. because this is where all the app logic runs, if our js thread is busy making a network request and we want to perform an animation, the animation is gonna lag and we do not get the desired result.

When we use the UI thread to use animation without disturbing our js thread, we get clean and performant animation.

The first issue that we discussed are-

let's suppose we want to animate the translateY value of a View.

<View style={{transform: [{translateY: translateValue}]}}/> ;

and we are doing this using the wrong approach,

let's create a state to hold translate value.

const[translateValue,setTranslateValue]=useState(0);

now to animate when our app renders

useEffect(()=>{

for(let i = 0 , i <200;i++){

setTimeout(()={

setTranslateValue(i)

},100*i)

}

},[])

This will animate translate value from 0 to 200 , but this will happen on the JavaScript thread and this will cause performance issues and will freeze or lag id js thread is busy making network request or calculating for logic

The Recommended way is to use Animated API of react-native that handles animation on the UI thread-

so ,

import {Animated} from 'react-native';

and we wrap the component we want to animate around animated using syntax -

//Animated.View, Animated.Text, Animated.Image etc...

<Animated.View style={{transform: [{translateY: translateValue}]}}/> ;

now to translate y value we wont use state , we will use Animated value and store in useRef-

const translateValue = useRef(new Animated.Value(0)).current;

and animate using Animated API using timing fucntion-

useEffect(()=>{

Animated.timing(translateValue,{

toValue:200,

useNativeDriver:true

})

},[])

Now this will animated the translate value from 0 to 200 ,you can also pass duration like-

Animated.timing(translateValue,{

toValue:200,

duration:2000, //this is in milliseconds

useNativeDriver:true

})

We are a seasoned ERP development company that excels in building custom enterprise solutions that are easy to scale. Our team uses agile methodologies to develop scalable enterprise applications with custom features. To learn more about our custom ERP software development services, drop us a line at [email protected].