I've been trying to use useState
inside useFocusEffect
. Following react-navigation I got something like this:
const [counter, setCounter] = useState(0);
useFocusEffect(
useCallback(() => {
console.log(counter);
}, [counter]),
);
Now the problem is that every time counter
updates, useFocusEffect
fires. What I want is for it to fire only when screen comes into focus. Now I've also tried doing this with navigation focus listener:
useEffect(() => {
const onFocus = navigation.addListener('focus', () => {
console.log(counter);
});
return onFocus;
}, [navigation, counter]);
It works, well partially. While the onFocus
function is performed only when screen comes into focus, useEffect
fires every time counter updates. Same thing happens when using redux-toolkit slices. How can I prevent this behaviour?
Update
I should add that removing counter
from dependency array prevents it from updating in subsequential runs. So I will rephrase the question. Is there a way to either fix useCallback
by preventing it from firing every time counter
updates or fix useEffect
so that it fires only on focus with counter
updated?
You included
counter
in the dependency array of your useEffect. This tells the useEffect to run every time a change is made tocounter
. See the docs for useEffect here: https://reactjs.org/docs/hooks-reference.html#useeffect