DEV Community

Cover image for Conquer Breakpoints with React's useBreakpoints Hook
Jack Vatcharat
Jack Vatcharat

Posted on

Conquer Breakpoints with React's useBreakpoints Hook

Image description

When building modern web apps, having a responsive design that works smoothly on all screen sizes isn’t just nice to have—it’s a must. A great way to achieve this is by handling mobile and desktop views differently. That’s where the useBreakpoints hook comes in! It’s a handy tool for developers to create user-friendly experiences across devices.

What’s the useBreakpoints Hook?

The useBreakpoints hook is a custom React hook that taps into Material-UI's useTheme and useMediaQuery hooks. It figures out the current screen size, so you can decide what to show or how to style things based on whether someone’s on a phone or a computer.

Image description

Why Use useBreakpoints?

  1. Better User Experience: By customizing the interface for mobile and desktop users, you can make sure everyone gets the best experience. Mobile users see a sleek, simplified design, while desktop users get to enjoy a more detailed layout.
  2. Cleaner Code: No more scattered media queries all over your CSS files. The useBreakpoints hook lets you handle responsive logic right in your components, making your code easier to read and maintain.
  3. Faster Performance: By showing only what’s needed for a specific screen size, you can reduce unnecessary data loading and speed up your app.
  4. Project Consistency: Using the useBreakpoints hook across your projects keeps things consistent and helps new team members quickly get up to speed.

How to Use the useBreakpoints Hook

Here’s a quick walkthrough of setting up and using the useBreakpoints hook in a React app.

Step 1: Set Up the Hook

First, create a custom hook using Material-UI's useTheme and useMediaQuery to determine the screen size.

import { useMediaQuery, useTheme } from '@mui/material';

/**
 * Custom hook to get the current state of breakpoints based on the theme.
 */
export const useBreakpoints = () => {
  const theme = useTheme();

  const isMd = useMediaQuery(theme.breakpoints.only('md'));

  return {
    isMd,
  };
};
Enter fullscreen mode Exit fullscreen mode

Step 2: Put the Hook to Work

Now, use the useBreakpoints hook in a component to display different layouts for mobile and desktop users. For instance, you can show a list for mobile users and a table for desktop users using Material-UI components.

import React from 'react';
import { useBreakpoints } from '/Users/jack/Work/SGInnovate/frontend/packages/shared/ui/utils/breakpoints';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, List, ListItem, Paper } from '@mui/material';

const ResponsiveComponent = () => {
  const { isMdDown } = useBreakpoints();

  const data = [
    { id: 1, name: 'Item 1', value: 'Value 1' },
    { id: 2, name: 'Item 2', value: 'Value 2' },
    { id: 3, name: 'Item 3', value: 'Value 3' },
  ];

  return (
    <div>
      {isMdDown ? (
        <List>
          {data.map((item) => (
            <ListItem key={item.id}>{item.name}: {item.value}</ListItem>
          ))}
        </List>
      ) : (
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Name</TableCell>
                <TableCell>Value</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {data.map((item) => (
                <TableRow key={item.id}>
                  <TableCell>{item.name}</TableCell>
                  <TableCell>{item.value}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </div>
  );
};

export default ResponsiveComponent;
Enter fullscreen mode Exit fullscreen mode

And that’s it! With the useBreakpoints hook, you can make your app responsive and user-friendly without breaking a sweat.

Wrapping It Up

The useBreakpoints hook is a simple yet powerful tool that makes managing responsive designs in React a lot easier. By tailoring your UI for different screen sizes, you can create a seamless experience for your users while keeping your code clean and maintainable. Whether you’re building a complex web app or a simple site, this hook can help you deliver polished, professional results. So go ahead, give it a try, and watch your app adapt like a pro!

Top comments (0)