Open In App

What is InteractionManager and how is it used ?

Last Updated : 16 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Interaction Manager is the native module that allows long-running work to be scheduled until an “interaction” has finished. We can call the runAfterInteractions() => {} to be continued interaction. We can also define our own interactions. It is used to run JavaScript smoothly:

Prerequisites:

Syntax:

InteractionManager.runAfterInteractions(() => {
// long-running synchronous task...
});

Following are the alternative options for scheduling to Interaction Manager:

  • requestAnimationFrame(): used for code that animates a view over time.
  • setImmediate/setTimeout(): used to run code later, note this may delay animations.
  • runAfterInteractions(): used to run code later, without delaying active animations.

The touch handling system of reacts native considers one or more active touches to be an ‘interaction’ and will delay runAfterInteractions() callbacks function until all touches have ended or been canceled.

InteractionManager also gives permission to applications to register your own animations by using an interaction ‘handle’ on animation start, and clearing it upon completion:

const handle = InteractionManager.createInteractionHandle();
InteractionManager.clearInteractionHandle(handle);

runAfterInteractions() runs a plain callback function or a PromiseTask() object with a general method that returns a Promise object. If a PromiseTask() is supplied, then it is executed before starting on the next task that might have been in the queue.

By default, queued tasks are executed in a group in one setImmediate() time. If setDeadline is called, then tasks will only be executed until the deadline, at which point execution will stop via setTimeout(), allowing events such as touches to start interactions and stop the execution of queued tasks from executing, making apps more responsive.

Why use Interaction Manager ?:

Interaction Manager is very important because of React Native threads. There are two threads available in React Native, one is a Javascript UI thread that handles drawing updates to the screen, and another thread is used for all tasks not on the UI thread.

Since there is only one thread for making UI updates, it causes overload and drops frames, especially during the execution of navigation screen animations. We have to use the Interaction Manager to ensure that our function is executed after these animations occur so that we do not drop frames on the UI thread. It is very difficult to draw a new screen while it is being animated and is often too much for the thread to handle.

Interaction Manager Methods:

  • runAfterInteractions(): This is used to schedule a function to run after all interactions have been completed.
static runAfterInteractions(callback)

  • createInteractionHandle(): This is used to notify the manager that an interaction has started.
static createInteractionHandle()

  • clearInteractionHandle(): This is used to notify the manager that an interaction has been completed.
static clearInteractionHandle(handle)

  • setDeadline(): A positive number is used to setTimeout to schedule any tasks after the eventLoopRunningTime hits the deadline value, otherwise by default all tasks will be executed in one setImmediate batch.
static setDeadline(deadline)

Steps to Create React JS Application:

Step 1: Install React Native using the following command 

npm i -g create-react-native-app

Step 2: Create a project

create-react-native-app Interaction-Manager

Step 3: Go to the project directory

cd Interaction-Manager

Step 4: Install the required packages by using the following command:

npm i --save-dev react react-dom 
npm i --save-dev react-native-web react-scripts

Project Structure:

Project structure 

The updated dependencies in package.json file.

"dependencies": {
"expo": "~49.0.15",
"expo-splash-screen": "~0.20.5",
"expo-status-bar": "~1.6.0",
"react-native": "0.72.6"
},
"devDependencies": {
"@babel/core": "^7.20.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-native-web": "^0.19.9",
"react-scripts": "^5.0.1"
}

Example 1: This example shows basic implementation of InteractionManager Function Component.

Javascript




// Filename - App.js
 
import { useState, useEffect } from "react";
import {
    Alert,
    Image,
    Animated,
    InteractionManager,
    Platform,
    StyleSheet,
    Text,
    View,
} from "react-native";
const useMount = func => useEffect(() => func(), []);
const useFadeIn = (duration = 2000) => {
    const [opacity] = useState(new Animated.Value(0));
    useMount(() => {
        Animated.timing(opacity, {
            toValue: 1,
            duration,
        }).start();
    });
    return opacity;
};
const Ball = ({ onShown }) => {
    const opacity = useFadeIn();
    useMount(() => {
        const interactionPromise = InteractionManager.runAfterInteractions();
        return () => interactionPromise.cancel();
    });
    return <View style={[styles.logo, { opacity }]} />;
}
function App() {
    return (
        <View style={styles.app}>
            <View style={styles.header}>
                <Text style={styles.title}>
                    Welcome To GFG</Text>
                <Image
                    source={{
                        uri:
                    }}
                    resizeMode="contain"
                    style={{ height: 80 }} />
            </View>
        </View>
    );
}
const styles = StyleSheet.create({
    app: {
        marginHorizontal: "auto",
        maxWidth: 500
    },
    logo: {
        height: 80
    },
    header: {
        padding: 20
    },
    title: {
        fontWeight: "bold",
        fontSize: "1.5rem",
        marginVertical: "1em",
        textAlign: "center"
    },
});
export default App;


Step to Run the Application: Start the Application using this command. 

npm start

 Output:

Example 2: This example shows implementation of InteractionManager Function Component Advance.

Javascript




// Filename - App.js
 
import React, { useRef, useState, useEffect } from 'react';
import { Animated, Image, Text, View } from 'react-native';
 
const FadeInView = (props) => {
    // Initial value for opacity: 0
    const fadeAnim = useRef(new Animated.Value(0)).current 
    useEffect(() => {
        Animated.timing(
            fadeAnim,
            {
                toValue: 1,
                duration: 7000,
            }
        ).start();
    }, [fadeAnim])
    return (
        <Animated.View
            style={{
                ...props.style,
                opacity: fadeAnim,
            }}>
            {props.children}
        </Animated.View>
    );
    return <View style={[styles.logo, { opacity }]} />;
}
 
export default () => {
    return (
        <View style=
        {{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <FadeInView>
                <Text style={{
                    fontWeight: "bold",
                    fontSize: "1.5rem",
                    color: "green",
                    marginVertical: "1em",
                    textAlign: "center"
                }}>
                    Welcome To GFG</Text>
                <Image
                    source={{ uri:
                    resizeMode="contain"
                    style={{ height: 80 }}
                />
            </FadeInView>
        </View>
    )
}


Step to Run the Application: Start the Application using this command. 

npm start

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads