Your destination for complete Tech news

How to detect screen resolution using React JS?

1.58K 0
< 1 min read

You can detect the screen resolution using JavaScript within a React component. Here’s how you can achieve this:

import React, { useState, useEffect } from 'react';

function ScreenResolutionDetector() {
  const [screenWidth, setScreenWidth] = useState(window.innerWidth);
  const [screenHeight, setScreenHeight] = useState(window.innerHeight);

  useEffect(() => {
    const handleResize = () => {

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
  }, []);

  return (
      <p>Screen Resolution:</p>
      <p>Width: {screenWidth}px</p>
      <p>Height: {screenHeight}px</p>

export default ScreenResolutionDetector;

In this example, the ScreenResolutionDetector component uses the useState and useEffect hooks to track the screen width and height. The useEffect hook listens for the resize event on the window object and updates the state with the current screen width and height when the window is resized.

The component then displays the current screen resolution in pixels.

Keep in mind that this approach provides the current screen dimensions, but not the actual screen resolution in DPI (dots per inch). If you need to determine the DPI or handle responsive design based on different screen sizes, you might need additional techniques and libraries.

Also, be aware that using the resize event to track screen size changes can be resource-intensive. Consider using debouncing or throttling techniques to optimize the event handling, especially if your application needs to handle frequent resizing events.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.