DEV Community

Cover image for React's Responsive Magic: Harnessing useCheckMobileScreen Hook ๐Ÿ”ฅ
Bilal Asghar
Bilal Asghar

Posted on

React's Responsive Magic: Harnessing useCheckMobileScreen Hook ๐Ÿ”ฅ

Hey fellow developers! Have you ever thought about how to make your React app look good on both small mobile screens and big desktop computers? You know, we have these things called media queries in CSS that help us with that. But sometimes, dealing with media queries can be tough and make things messy. Well, guess what? You don't need to worry anymore!
Let me introduce you to a new friend: the 'useCheckMobileScreen' custom hook. It's here to make things easier for you!

Meet the Hook in Action

Image description
Now, let's see how this magical hook works in your code:

import { useEffect, useState } from "react";

const useCheckMobileScreen = () => {
  const [width, setWidth] = useState(window.innerWidth);

  const handleWindowSizeChange = () => {
    setWidth(window.innerWidth);
  };

  useEffect(() => {
    window.addEventListener("resize", handleWindowSizeChange);
    return () => {
      window.removeEventListener("resize", handleWindowSizeChange);
    };
  }, []);

  return {
    isMobile: width <= 768,
  };
};

export default useCheckMobileScreen;
Enter fullscreen mode Exit fullscreen mode
import useCheckMobileScreen from "hooks";
const App = () => {
  const { isMobile } = useCheckMobileScreen();
  return (
    <>
      {isMobile ? (
        <div>Render something for Mobile Only</div>
      ) : (
        <div>Render Something on Desktop Only</div>
      )}

      {/* Also In Case if you have different styles for mobile & desktop */}
      <p
        className={`${
          isMobile ? "mobile-screen-paragraph" : "desktop-screen-paragraph"
        }`}
      >
        Text Goes here
      </p>
    </>
  );
};
export default App;

Enter fullscreen mode Exit fullscreen mode

Wrapping It Up

So there you have it, the secret to making your React app a superstar on every screen: the useCheckMobileScreen hook! It's a simple little helper that makes a big difference in creating a user-friendly and adaptable app. So go ahead, give it a try, and watch your app shine bright on screens big and small. Happy coding, and keep spreading that responsive magic! ๐ŸŒŸ๐Ÿ“ฑ๐Ÿ’ป

Top comments (2)

Collapse
 
certifieddev19960101 profile image
certifieddev0101

Wowowowo~~~~~

Collapse
 
robinamirbahar profile image
Robina

Nice Work