Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
React matchMedia - is there a cleaner way to do this?

I need to render different components based on the screen size -

If the screen is 1012px or under then setComponent('box');

If the screen is 1460px or under then setComponent('info);

Else if the screen is above 1460px then setComponent('both');

This is how I'm currently doing it -

  if (typeof window !== 'undefined' && showComponents) {
    window.matchMedia('(max-width: 1012px)').addEventListener('change', (event) => {
      if (event.matches) {
        setComponent('box');
      }
    });

    window.matchMedia('(max-width: 1460px)').addEventListener('change', (event) => {
      if (event.matches) {
        setComponent('info');
      }
    });

    window.matchMedia('(min-width: 1460px)').addEventListener('change', (event) => {
      if (event.matches) {
        setComponent('both');
      }
    });
  }

Before this, I was using window.innerWidth however I read that matchMedia is a better solution to this. But looking at the code above, I am not sure if there is a cleaner way of writing it. Also do the listeners need to be removed?

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!