DEV Community

Cover image for Mastering React's useMediaQuery Hook
Labby for LabEx

Posted on

Mastering React's useMediaQuery Hook

Introduction

MindMap

This article covers the following tech skills:

Skills Graph

In this lab, we will explore the use of the useMediaQuery hook in React. This hook allows us to check if the current environment matches a given media query and return the appropriate value. We will learn how to use this hook to create responsive components that change their behavior based on the screen size.

React useMediaQuery Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This function checks if the current environment matches a given media query and returns the appropriate value.

  • First, check if Window and Window.matchMedia() exist. If not (e.g. in an SSR environment or unsupported browser), return whenFalse.
  • Use Window.matchMedia() to match the given query. Cast its matches property to a boolean and store it in a state variable, match, using the useState() hook.
  • Use the useEffect() hook to add a listener for changes and to clean up the listeners after the hook is destroyed.
  • Finally, return either whenTrue or whenFalse based on the value of match.
const useMediaQuery = (query, whenTrue, whenFalse) => {
  if (
    typeof window === "undefined" ||
    typeof window.matchMedia === "undefined"
  ) {
    return whenFalse;
  }

  const mediaQuery = window.matchMedia(query);
  const [match, setMatch] = React.useState(!!mediaQuery.matches);

  React.useEffect(() => {
    const handler = () => setMatch(!!mediaQuery.matches);
    mediaQuery.addListener(handler);
    return () => mediaQuery.removeListener(handler);
  }, [mediaQuery]);

  return match ? whenTrue : whenFalse;
};
Enter fullscreen mode Exit fullscreen mode
const ResponsiveText = () => {
  const text = useMediaQuery(
    "(max-width: 400px)",
    "Less than 400px wide",
    "More than 400px wide"
  );

  return <span>{text}</span>;
};

ReactDOM.createRoot(document.getElementById("root")).render(<ResponsiveText />);
Enter fullscreen mode Exit fullscreen mode

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useMediaQuery Hook lab. You can practice more labs in LabEx to improve your skills.


Want to learn more?

Join our Discord or tweet us @WeAreLabEx ๐Ÿ˜„

Top comments (0)