Skip to content

Instantly share code, notes, and snippets.

@d-johnston
Created June 12, 2025 18:12
Show Gist options
  • Select an option

  • Save d-johnston/5bfaf354d1bc6695438c56eebd46b9fc to your computer and use it in GitHub Desktop.

Select an option

Save d-johnston/5bfaf354d1bc6695438c56eebd46b9fc to your computer and use it in GitHub Desktop.
Example of how useEffects still run when you switch away from a screen
const [count, setCount] = useState(0)
const [slowCount, setSlowCount] = useState(0)
const [isToggled, setIsToggled] = useState(false)
useEffect(() => {
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)
}
}, [])
useEffect(() => {
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