Closed
Description
Hello, @kentcdodds! I have one question left about the Advanced React Hooks section (excercise 6). I want to make clear the use case of mounted variable in the code below. Query value never changes, so on unmount we just remove the change event listener added to matchMedia, because of that onChange function won't be called if the component gets unmounted.
what's the exact reason for checking mounted inside matchMedia onChange handler function? (mounted variable is declared and initialized inside useEffect callback, so because of that the use case is confusing for me). Thanks in advance!)
React.useEffect(() => {
let mounted = true // <--
const mql = window.matchMedia(query)
function onChange() {
if (!mounted) {
return
}
setState(Boolean(mql.matches))
}
mql.addEventListener('change', onChange)
setState(mql.matches)
return () => {
mounted = false
mql.removeEventListener('change', onChange)
}
}, [query])
Metadata
Metadata
Assignees
Labels
No labels