How to use matchMedia to create a performant custom viewport hook

By Dave Bitter

3 min read

Unfortunately, sometimes you need to write viewport-based logic in your JavaScript code. Usually, this is done with a listener on the window for a resize. Let’s look at a better way.

How to use _matchMedia_ to create a performant custom viewport hook
Authors

What’s wrong with listening for the resize event?

Nothing really, it does the job. This has been the way for years now. There is a downside that comes with this solution, though. Let’s say you have four breakpoints:

  • sm with a maximum width of 767 pixels
  • md with a minimum width of 768 pixels
  • lg with a minimum width of 1024 pixels
  • xl with a minimum width of 1200 pixels

You’re only really interested in these four pixel values. However, when listening to the resize event, you’ll get an update for every pixel value in between as well. Let's say you are implementing a utility for your React.js project to offer this. A custom React.js hook you can write will probably look a bit like this:

import { useEffect, useState } from 'react'

type ViewportBreakpoint = 'sm' | 'md' | 'lg' | 'xl'

const useViewportBreakpoint = () => {
  const [viewportBreakpoint, setViewportBreakpoint] = useState<ViewportBreakpoint>('sm')

  useEffect(() => {
    const onResize = () => {
      if (window.innerWidth < 768) {
        setViewportBreakpoint('sm')
        return
      }

      if (window.innerWidth < 1024) {
        setViewportBreakpoint('md')
        return
      }

      if (window.innerWidth < 1200) {
        setViewportBreakpoint('lg')
        return
      }

      setViewportBreakpoint('xl')
    }

    window.addEventListener('resize', onResize)
    onResize()

    return () => window.removeEventListener('resize', onResize)
  }, [])

  return viewportBreakpoint
}

export default useViewportBreakpoint

Sure, you could use requestAnimationFrame to optimize this a bit further, but inherently you’re going to receive far more updates than you actually need.

Cool, so how does matchMedia fix that?

On the window object, you’ll find a method called matchMedia. With this method, you can listen for a media query, just like in CSS, to respond to. The basic usage looks like this:

const mql = window.matchMedia('(min-width: 768px)')

const handleQueryChange = ({ matches }) => {
  console.log(matches) // true or false
}

mql.addEventListener('change', handleQueryChange)

That’s it! Every time the viewport passed 768 pixels, you’ll receive an update. You can then handle your business logic based on whether the media query is met.

Let’s make a custom hook!

Now, let’s take the above principle and create a custom hook that will support all four of the viewport breakpoints:

import { useEffect, useState } from 'react'

type ViewportBreakpoint = 'sm' | 'md' | 'lg' | 'xl'

const useViewportBreakpoint = () => {
  const [viewportBreakpoint, setViewportBreakpoint] = useState<ViewportBreakpoint>('sm')

  useEffect(() => {
    const smQuery = window.matchMedia('(max-width: 767px)')
    const mdQuery = window.matchMedia('(min-width: 768px) and (max-width: 1023px)')
    const lgQuery = window.matchMedia('(min-width: 1024px) and (max-width: 1199px)')
    const xlQuery = window.matchMedia('(min-width: 1200px)')

    const handleSmQueryChange = ({ matches }: { matches: boolean }) =>
      matches && setViewportBreakpoint('sm')
    const handleMdQueryChange = ({ matches }: { matches: boolean }) =>
      matches && setViewportBreakpoint('md')
    const handleLgQueryChange = ({ matches }: { matches: boolean }) =>
      matches && setViewportBreakpoint('lg')
    const handleXlQueryChange = ({ matches }: { matches: boolean }) =>
      matches && setViewportBreakpoint('xl')

    smQuery.addEventListener('change', handleSmQueryChange)
    mdQuery.addEventListener('change', handleMdQueryChange)
    lgQuery.addEventListener('change', handleLgQueryChange)
    xlQuery.addEventListener('change', handleXlQueryChange)

    handleSmQueryChange({ matches: smQuery.matches })
    handleMdQueryChange({ matches: mdQuery.matches })
    handleLgQueryChange({ matches: lgQuery.matches })
    handleXlQueryChange({ matches: xlQuery.matches })

    return () => {
      smQuery.removeEventListener('change', handleSmQueryChange)
      mdQuery.removeEventListener('change', handleMdQueryChange)
      lgQuery.removeEventListener('change', handleLgQueryChange)
      xlQuery.removeEventListener('change', handleXlQueryChange)
    }
  }, [])

  return viewportBreakpoint
}

export default useViewportBreakpoint

Wow! Quite a bit of boilerplate. As you can only listen for on media query, you’ll have to quadruple the code. Before we optimize this, let’s have a look at the different parts.

Firstly, you now have to set a minimum and maximum width for the different media queries. Previously, you could bail out as soon as a viewport was matched. As these are all different events, they will all trigger. This can cause multiple media queries to match. By adding maximum widths, you can circumvent this.

Secondly, the callback function when a change event is detected does receive the media query it matched against, but we then have to map which ViewportBreakpoint it belongs to. If you don’t want to add this complexity, you have to create four separate callbacks.

Finally, as you have to add four event listeners, you have to remove four of them as well. This is a bit annoying.

Time to refactor

Firstly, you could refactor the callback to a single one and check each media query to conditionally set the value for the active viewport breakpoint:

import { useEffect, useState } from 'react'

type ViewportBreakpoint = 'sm' | 'md' | 'lg' | 'xl'

const useViewportBreakpoint = () => {
  const [viewportBreakpoint, setViewportBreakpoint] = useState<ViewportBreakpoint>('sm')

  useEffect(() => {
    const smQuery = window.matchMedia('(max-width: 767px)')
    const mdQuery = window.matchMedia('(min-width: 768px) and (max-width: 1023px)')
    const lgQuery = window.matchMedia('(min-width: 1024px) and (max-width: 1199px)')
    const xlQuery = window.matchMedia('(min-width: 1200px)')

    const checkMatch = () => {
      smQuery.matches && setViewportBreakpoint('sm')
      mdQuery.matches && setViewportBreakpoint('md')
      lgQuery.matches && setViewportBreakpoint('lg')
      xlQuery.matches && setViewportBreakpoint('xl')
    }

    smQuery.addEventListener('change', checkMatch)
    mdQuery.addEventListener('change', checkMatch)
    lgQuery.addEventListener('change', checkMatch)
    xlQuery.addEventListener('change', checkMatch)
    checkMatch()

    return () => {
      smQuery.removeEventListener('change', checkMatch)
      mdQuery.removeEventListener('change', checkMatch)
      lgQuery.removeEventListener('change', checkMatch)
      xlQuery.removeEventListener('change', checkMatch)
    }
  }, [])

  return viewportBreakpoint
}

export default useViewportBreakpoint

This works because you added the maximum widths. Only one will ever match and update the state of the viewport breakpoint.

This does still feel a bit repetitive, though. How can you make this more DRY? Let’s create an array with multiple viewport breakpoints and their media query. You can then loop over this array and execute the logic:

import { useEffect, useState } from 'react'

type ViewportBreakpoint = 'sm' | 'md' | 'lg' | 'xl'
type ViewportBreakpointConfig = {
  size: ViewportBreakpoint
  mql: MediaQueryList
}

const useViewportBreakpoint = () => {
  const [viewportBreakpoint, setViewportBreakpoint] = useState<ViewportBreakpoint>('sm')

  useEffect(() => {
    const mqls: ViewportBreakpointConfig[] = [
      { size: 'sm', mql: window.matchMedia('(max-width: 767px)') },
      { size: 'md', mql: window.matchMedia('(min-width: 768px) and (max-width: 1023px)') },
      { size: 'lg', mql: window.matchMedia('(min-width: 1024px) and (max-width: 1199px)') },
      { size: 'xl', mql: window.matchMedia('(min-width: 1200px)') },
    ]

    const checkMatch = () =>
      mqls.forEach(({ size, mql }) => mql.matches && setViewportBreakpoint(size))

    mqls.forEach(({ mql }) => mql.addEventListener('change', checkMatch))
    checkMatch()

    return () => {
      mqls.forEach(({ mql }) => mql.removeEventListener('change', checkMatch))
    }
  }, [])

  return viewportBreakpoint
}

export default useViewportBreakpoint

There you have it! You can now use this custom hook in your React.js application to execute viewport-based logic.

Final thoughts

Once in a while, you get surprised about a better way of doing something you’ve been doing the same for years. So, is this a new technique? Well, quite the opposite! The support for matchMedia is great:

Data on support for the matchmedia feature across the major browsers from caniuse.com

The next time you have to create a similar utility, try matchMedia out!


Upcoming events

  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design
  • The Leadership Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🙋‍♀️ drinks 21:00 – 🍻 See you next time? First Round of Talks: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Leadership Meetup
  • Coven of Wisdom - Herentals - Spring `24 edition

    Join us for an exciting web technology meetup where you’ll get a chance to gain valuable insights and knowledge about the latest trends in the field. Don’t miss out on this opportunity to expand your knowledge, network with fellow developers, and discover new and exciting possibilities. And the best part? Food and drinks are on us! Johan Vervloet - Event sourced wiezen; an introduction to Event Sourcing and CQRS Join me on a journey into the world of CQRS and Event Sourcing! Together we will unravel the misteries behind these powerful concepts, by exploring a real-life application: a score app for the 'Wiezen' card game.Using examples straight from the card table, we will delve into the depths of event sourcing and CQRS, comparing them to more traditional approaches that rely on an ORM.We will uncover the signs in your own database that indicate where event sourcing can bring added value. I will also provide you with some tips and pointers, should you decide to embark on your own event sourcing adventure. Filip Van Reeth - WordPress API; "Are you talking to me?" What if the WordPress API could be one of your best friends? What kind of light-hearted or profound requests would it share with you? In this talk, I would like to introduce you to it and ensure that you become best friends so that together you can have many more pleasant conversations (calls). Wanna be friends? Please note that the event or talks will be conducted in Dutch. Want to give a talk? Send us your proposal at meetup.herentals@iodigital.com 18:00 - 19:00: Food/Drinks/Networking 19:00 - 21:00: Talks 21:00 - 22:00: Networking Thursday 30th of May, 18h00 - 22h00 CET iO Campus Herentals, Zavelheide 15, Herentals

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Spring `24 edition

Share