Skip to content

useDebugValue: useMedia (Advanced React Hooks) #200

Closed
@Str4nge1

Description

@Str4nge1

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions