Course contentsShow
← React Native
Lesson 363 of 1,5554. Flexbox and Native StylingFree lesson

Responsive Design with Media Query Hooks

Implement custom hooks that provide device-width breakpoints to the layout system.

In this lesson, you will learn how to build a custom hook that transforms raw screen dimensions into semantic breakpoints, allowing your components to react fluidly to layout changes.

The "Why" Behind Breakpoints

In React Native, we don’t have CSS media queries like @media (min-width: 768px). Instead, we rely on the useWindowDimensions hook from the react-native package. However, hardcoding logic like if (width > 768) throughout your codebase leads to "magic numbers" that are hard to maintain. By abstracting this into a custom hook, we create a single source of truth for our app's responsiveness.

Implementing the Custom Hook

We can create a useDeviceType hook that categorizes the screen width into standard tiers: mobile, tablet, or desktop.

import { useWindowDimensions } from 'react-native';

export const useDeviceType = () => {
  const { width } = useWindowDimensions();

  return {
    isMobile: width < 600,
    isTablet: width >= 600 && width < 1024,
    isDesktop: width >= 1024,
  };
};

Applying the Logic

Once this hook is defined, using it in your components becomes clean and declarative. You can switch styles or even swap out entire sub-components based on the current breakpoint:

const MyLayout = () => {
  const { isMobile, isTablet } = useDeviceType();

  return (
    <View style={{ padding: isMobile ? 10 : 40 }}>
      <Text>{isMobile ? "Compact View" : "Spacious View"}</Text>
    </View>
  );
};

By using this approach, your UI logic stays focused on intent ("is this mobile?") rather than pixel counting. When you need to change your breakpoint threshold, you only update the custom hook in one location, and your entire application updates automatically. This modular strategy ensures your layout engine remains robust as you scale your app across different form factors, from foldable phones to large tablets.

Key Takeaway: Abstracting screen dimensions into custom hooks turns fragile pixel-based calculations into clear, maintainable semantic states that make your layout truly adaptive.