As a frontend developer, creating responsive interfaces is one of your main responsibilities. While CSS media queries or Tailwind’s built-in screen sizes (powered by media queries, of course) are incredibly powerful, there are times when you need more dynamic screen size detection.
For example, if you visit airbnb.com, you’ll notice differences between the desktop and mobile views. On the desktop, the home filters appear in a modal (or dialog) centered on the screen. On mobile, however, the same filters appear in a drawer that slides smoothly from the bottom of the screen. This behavior isn’t just CSS magic—it’s achieved through dynamic screen size detection with JavaScript.
Sure, there are many packages to handle screen size detection, but why install a package when you can build it yourself?
In this article, I’ll guide you through creating custom screen size hooks for React, Vue, and Angular to tackle real-world responsive design challenges.
Let’s save our projects from yet another package or plugin and do it ourselves!
A Simple Approach: Using window.innerWidth
If you run this code in your browser’s console, it will tell you the current screen width of your device. Try resizing your screen, and you’ll see how the value updates. Using this API, we can create reusable functions or hooks for any project:
Implementing a Cross-Framework Screen Size Hook
Check Website Screen Size with Pure JavaScript
export function getScreenSize() {
const breakpoints = {
mobile: 640,
tablet: 1024,
};
const width = window.innerWidth;
if (width < breakpoints.mobile) return 'mobile';
if (width < breakpoints.tablet) return 'tablet';
return 'desktop';
}
You can use this function like so:
function checkScreenSize() {
const screenType = getScreenSize();
console.log(`Current screen: ${screenType}`);
// OR
const Hero = screenType === 'mobile' ? <MobileHero /> : <DesktopHero />;
}
Simple React Hook to Check Website Screen Sizes
import { useState, useEffect } from 'react';
interface ScreenSize {
width: number;
height: number;
isMobile: boolean;
isTablet: boolean;
isDesktop: boolean;
}
function useScreenSize(): ScreenSize {
const [screenSize, setScreenSize] = useState<ScreenSize>({
width: window.innerWidth,
height: window.innerHeight,
isMobile: window.innerWidth < 640,
isTablet: window.innerWidth >= 640 && window.innerWidth < 1024,
isDesktop: window.innerWidth >= 1024,
});
useEffect(() => {
const handleResize = () => {
setScreenSize({
width: window.innerWidth,
height: window.innerHeight,
isMobile: window.innerWidth < 640,
isTablet: window.innerWidth >= 640 && window.innerWidth < 1024,
isDesktop: window.innerWidth >= 1024,
});
};
window.addEventListener('resize', handleResize);
// Cleanup listener
return () => window.removeEventListener('resize', handleResize);
}, []);
return screenSize;
}
// Usage example
function ResponsiveComponent() {
const { isMobile, isDesktop } = useScreenSize();
return (
<div>
{isMobile && <MobileView />}
{isDesktop && <DesktopView />}
</div>
);
}
Vue 3 Composition API Hook to Check Website Screen Sizes
import { ref, onMounted, onUnmounted } from 'vue';
function useScreenSize() {
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);
const isMobile = ref(window.innerWidth < 640);
const isTablet = ref(window.innerWidth >= 640 && window.innerWidth < 1024);
const isDesktop = ref(window.innerWidth >= 1024);
const handleResize = () => {
width.value = window.innerWidth;
height.value = window.innerHeight;
isMobile.value = window.innerWidth < 640;
isTablet.value = window.innerWidth >= 640 && window.innerWidth < 1024;
isDesktop.value = window.innerWidth >= 1024;
};
onMounted(() => {
window.addEventListener('resize', handleResize);
});
onUnmounted(() => {
window.removeEventListener('resize', handleResize);
});
return { width, height, isMobile, isTablet, isDesktop };
}
// Usage in a Vue component
export default {
setup() {
const { isMobile, isDesktop } = useScreenSize();
return { isMobile, isDesktop };
},
};
Angular Service Approach to Check Screen Sizes
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ScreenSizeService {
private screenWidth = new BehaviorSubject<number>(window.innerWidth);
private screenHeight = new BehaviorSubject<number>(window.innerHeight);
public width$ = this.screenWidth.asObservable();
public height$ = this.screenHeight.asObservable();
public isMobile$ = new BehaviorSubject<boolean>(window.innerWidth < 640);
public isTablet$ = new BehaviorSubject<boolean>(
window.innerWidth >= 640 && window.innerWidth < 1024
);
public isDesktop$ = new BehaviorSubject<boolean>(window.innerWidth >= 1024);
constructor() {
window.addEventListener('resize', this.handleResize.bind(this));
}
private handleResize() {
const width = window.innerWidth;
this.screenWidth.next(width);
this.screenHeight.next(window.innerHeight);
this.isMobile$.next(width < 640);
this.isTablet$.next(width >= 640 && width < 1024);
this.isDesktop$.next(width >= 1024);
}
}
// Usage in a component
@Component({
selector: 'app-responsive',
template: `
<div *ngIf="screenService.isMobile$ | async">Mobile View</div>
<div *ngIf="screenService.isDesktop$ | async">Desktop View</div>
`,
})
export class ResponsiveComponent {
constructor(public screenService: ScreenSizeService) {}
}
That’s how to check for website screen sizes
It’s as simple as that! You just saved yourself the hassle of installing third-party plugins or packages.
Remember, you can extend these screen size variables to suit your project requirements.
If your project requires frequent resize
Event listeners, remember to use debounce to optimize performance. Debouncing prevents unnecessary re-renders and improves the user experience.
Let me know if you’d like further tweaks!
Leave a Reply