Wednesday, November 27, 2024
Google search engine
HomeLanguagesWhat is InteractionManager and how is it used ?

What is InteractionManager and how is it used ?

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

Syntax:

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

Following are the alternatives options for scheduling to Interaction Manager:

  1. requestAnimationFrame(): used for code that animates a view over time.
  2. setImmediate/setTimeout(): used to run code later, note this may delay animations.
  3. 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:

var 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.

Methods:

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

static runAfterInteractions(callback)

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

static createInteractionHandle()

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

static clearInteractionHandle(handle)

4. 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)

Create ReactJS Application: To create react app follow the steps:

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 folder named fast-refresh

$ cd Interaction-Manager

Step 4: Install the required package. We require 4 packages to run the interaction manager in react native. 

  1. React 
  2. React DOM 
  3. React Native web
  4. React script

Install these packages by using the following command:

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

Step 5: Start the npm package manager 

$ npm start

Project Structure: We see the implementation of an interaction manager, so we removed unnecessary files from the project file directory. Then our project structure looks like this:

Project structure 

Example 1: InteractionManager Function Component Basic:

  • App.js

Javascript




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;


 Output:

 

Example 2: InteractionManager Function Component Advance:

  • App.js

Javascript




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>
    )
}


Output:

 

Conclusion: In this article, we covered two examples that illustrate the interaction manager concept.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments