Created
June 12, 2025 18:19
-
-
Save d-johnston/5dc4d52f5c80bfe3fe8674030041c280 to your computer and use it in GitHub Desktop.
React Navigation (for React Native) showing their useFocusEffect which stops a counting mechanism when the page focus is lost
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const [count, setCount] = useState(0) | |
| const [slowCount, setSlowCount] = useState(0) | |
| const [isToggled, setIsToggled] = useState(false) | |
| useFocusEffect( | |
| useCallback(() => { | |
| console.log('slowCount useEffect ran') | |
| const interval = setInterval(() => { | |
| console.log('slow count incremented') | |
| setSlowCount((prevState) => prevState + 1) | |
| }, 15000) | |
| return () => { | |
| console.log('slowCount useEffect unmounted') | |
| clearInterval(interval) | |
| } | |
| }, []), | |
| ) | |
| useFocusEffect( | |
| useCallback(() => { | |
| console.log(`fast count useEffect ran with slowCount = ${slowCount}`) | |
| setCount(0) | |
| const interval = setInterval(() => { | |
| console.log('count incremented') | |
| setCount((prevState) => prevState + 1) | |
| }, 2000) | |
| return () => { | |
| console.log(`fast useEffect unmounted with slowCount = ${slowCount}`) | |
| clearInterval(interval) | |
| } | |
| }, [slowCount]), | |
| ) | |
| useEffect(() => { | |
| if (isToggled) { | |
| console.log(`count incremented to ${count + 1}`) | |
| setCount((prevState) => prevState + 1) | |
| } | |
| }, [isToggled]) | |
| return ( | |
| <View> | |
| <Body>Testing effects: isToggled? {isToggled ? 'true\n' : 'false\n'}</Body> | |
| <Body>Testing effects: count: {count}!!!{'\n'}</Body> | |
| <Button label={isToggled ? 'toggle off' : 'toggle on'} onPress={() => setIsToggled((prevState) => !prevState)}/> | |
| </View> | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment