Last active
December 20, 2022 20:24
-
-
Save kivircik-parantez/3f6adc8c3d516a665c66a3a7162d4239 to your computer and use it in GitHub Desktop.
UseEffect - Set up a subscription in a function component
This file contains 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
import { useEffect, useState } from 'react'; | |
function ComponentName() { | |
const [data, setData] = useState(null); | |
useEffect(() => { | |
// Create a subscription | |
const subscription = someDataStream.subscribe(data => { | |
setData(data); | |
}); | |
// Clean up the subscription when the component unmounts | |
return () => { | |
subscription.unsubscribe(); | |
}; | |
}, []); // The empty array specifies that this effect should only run once, on mount | |
return ( | |
<div> | |
{data ? <p>{data}</p> : <p>Loading data...</p>} | |
</div> | |
); | |
} |
This file contains 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
useEffect(() => { | |
// Create a subscription | |
const subscription = someDataStream.subscribe(data => { | |
setData(data); | |
}); | |
// Clean up the subscription when the component unmounts | |
return () => { | |
subscription.unsubscribe(); | |
}; | |
}, [prop]); // The prop is included in the dependencies array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment