'Is there a way to trigger useFocusEffect every time the screen gets focused with no dependencies at all?
I have been reading react native documentation and some other posts about this topic and it seems there is no way to trigger an action on react native every time a screen is rendered. I was planning to fetch data that might eventually change so i need to fetch that data everytime the user opens up that screen.
UseFocusEffect should indeed work for this matter but it only happens to trigger once. Here is one of the multiple chunks of code i have tried so far:
useFocusEffect(
useCallback(() => {
const loadData = async () => {
//fetch data
};
loadData();
}, [])
);
Thanks in advance
Solution 1:[1]
For your solution, there might be two ways to solve.
Way 1: By using isFocused from react-navigation/native.
import { useIsFocused } from '@react-navigation/native';
const isFocused = useIsFocused();
useEffect(() => {
if (isFocused) {
console.log('In inFocused Block', isFocused);
loadData();
}
}, [isFocused]);
const loadData = async () => { };
Way 2: By using Navigation Listener
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
console.log('In Navigation Add Listener Block');
loadData();
return unsubscribe;
}, [navigation]);
In both ways, it will render every-time when the page is load or Get focused!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mihir B |
