Skip to content

Instantly share code, notes, and snippets.

@kivircik-parantez
Last active December 20, 2022 20:24
Show Gist options
  • Save kivircik-parantez/3f6adc8c3d516a665c66a3a7162d4239 to your computer and use it in GitHub Desktop.
Save kivircik-parantez/3f6adc8c3d516a665c66a3a7162d4239 to your computer and use it in GitHub Desktop.
UseEffect - Set up a subscription in a function component
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>
);
}
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