Home > Software design >  Is there a hook that runs on application start up?
Is there a hook that runs on application start up?

Time:11-26

I was wondering if there is a library that contains a hook that runs on application open, or if there is a way to run functions when the app opens up (only in that instance without using any timed function)

CodePudding user response:

If you're building an app and going to have multiple screens look at React Navigations focus:

import * as React from 'react';
import { View } from 'react-native';

function ProfileScreen({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // The screen is focused
      // Call any action
    });

    // Return the function to unsubscribe from the event so it gets removed on unmount
    return unsubscribe;
  }, [navigation]);

  return <View />;
}

Docs:

https://reactnavigation.org/docs/function-after-focusing-screen/

Expo link example:

https://snack.expo.io/?platform=android&name=Call a function when focused screen changes | React Navigation&dependencies=@expo/vector-icons@*,@react-native-community/masked-view@*,react-native-gesture-handler@*,react-native-pager-view@*,react-native-paper@^4.7.2,react-native-reanimated@*,react-native-safe-area-context@*,react-native-screens@*,react-native-tab-view@^3.0.0,@react-navigation/[email protected],@react-navigation/[email protected],@react-navigation/[email protected],@react-navigation/[email protected],@react-navigation/[email protected],@react-navigation/[email protected],@react-navigation/[email protected],@react-navigation/[email protected]&hideQueryParams=true&sourceUrl=https://reactnavigation.org/examples/6.x/simple-focus-effect.js

CodePudding user response:

It looks like there is no such library.

CodePudding user response:

I'll give you an example:

import React, { useState } from 'react'

const Player = props => {
const [playerList, setPlayer] = useState([ ])

useEffect(() => {
fetch('URL')
  .then(res => res.json())
  .then(fetchedPlayers => setPlayer(fetchedPlayers))
}, [ ])
}

We pass an empty array as the second argument. This will tell React to call the first useEffect() function only when it is rendered for the first time, just like we did with componentDidMount().

  • Related