0

I am using react-responsive in development.

Let's say I have a file called responsive.js.

  const isBigScreen = useMediaQuery({ query: '(min-width: 1824px)' })
  const isTabletOrMobile = useMediaQuery({ query: '(max-width: 1224px)' })
  const isPortrait = useMediaQuery({ query: '(orientation: portrait)' })
  const isRetina = useMediaQuery({ query: '(min-resolution: 2dppx)' })

I want to use these variable without import them in every file. Is it possible?

For example, A.jsx

...
  return <div>
    <h1>Device Test!</h1>
    {isDesktopOrLaptop && <p>You are a desktop or laptop</p>}
    {isBigScreen && <p>You  have a huge screen</p>}
  </div>

B.jsx

  ...
  return <div>
    <h1>Device Test!</h1>
    {isDesktopOrLaptop && <p>You are a desktop or laptop</p>}
    <p>Your are in {isPortrait ? 'portrait' : 'landscape'} orientation</p>
    {isRetina && <p>You are retina</p>}
  </div>

Vue.js have vue-mq which can achieve what I want.

CCCC
  • 5,665
  • 4
  • 41
  • 88

1 Answers1

0

Firstly, you absolutely cannot use hooks like this. Hooks in React are made to be called synchronously on the top level of a component and in every single rerender, in the very same order. Check the docs

function Component() {
  // This is correct
  const myValue = useMyHook();
  ...
}

// This is incorrect
const myValue = useMyHook();

function Component() {
  ...
}

// This is also incorrect
function Component(props) {
  if (props.someValue) return ...
  
  // useMyHook will not be called on every rerender
  // and this will break React
  const myValue = useMyHook();
  ...
}

That said, you can extract your logic into custom hooks

export const useBigScreen = () => useMediaQuery({ query: '(min-width: 1824px)' });
export const usePortrait = () => useMediaQuery({ query: '(orientation: portrait)' })

And use them like

function Component() {
  const isPortrait = usePortrait();

  // do something with isPortrait
  ...
}

You'll still need to import/export those unless you use a build level library like unplugin auto import

Diego Fidalgo
  • 480
  • 3
  • 8