Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How splitting useEffect calls simplifies code, and reduces bugs
// ATTEMPT 1 - everything in one useEffect
React.useEffect(() => {
if (screenVideoTrack) {
createScreenShareOffer()
} else {
// 🐞 called before share, on mount
revokeScreenShareOffer()
}
// 🐞 called even if screen was never shared
return () => {
revokeScreenShareOffer()
}
}, [screenVideoTrack])
// ATTEMPT 2 - one use effect, but track transitions
const previousTrack = usePrevious(screenVideoTrack)
const previousTrackRef = React.useRef(previousTrack)
React.useEffect(() => {
previousTrackRef.current = previousTrack
})
React.useEffect(() => {
if (screenVideoTrack && !previousTrackRef.current) {
createScreenShareOffer()
} else if (previousTrackRef.current && !screenVideoTrack) {
revokeScreenShareOffer()
}
return () => {
if (screenVideoTrack) { // not even sure this is right
revokeScreenShareOffer()
}
}
}, [screenVideoTrack])
// ATTEMPT 3 - split into two useEffect calls
React.useEffect(() => {
if (screenVideoTrack) {
createScreenShareOffer()
}
}, [screenVideoTrack])
React.useEffect(() => {
if (screenVideoTrack) {
return () => {
revokeScreenShareOffer()
}
}
}, [screenVideoTrack])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment