Skip to content

useDebugValue: useMedia (Advanced React Hooks) #200

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Str4nge1 opened this issue Jan 23, 2023 · 2 comments
Closed

useDebugValue: useMedia (Advanced React Hooks) #200

Str4nge1 opened this issue Jan 23, 2023 · 2 comments

Comments

@Str4nge1
Copy link

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])
@kentcdodds
Copy link
Member

Hi! I'll give this a read during office hours this week :)

@kentcdodds
Copy link
Member

Answered in office hours just now: https://www.youtube.com/watch?v=BT3LWn5q8z8

I hope that helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants