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:
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()
.