Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
How to get device width/height in React without calling the window object

Is there a way to access device width or height in React or Next.js without using "window." or "document.". I understand we can get this with the hook useEffect and we don't have this error:

ReferenceError: window is not defined

but that's an overkill if I just need to access the width once

import { useEffect, useState } from "react";

const LayoutContainer = ({ Component, pageProps }) => {
  const [mobile, setMobile] = useState(true);

  useEffect(() => {
    console.log(window.innerWidth < 450, window.innerWidth);
    setMobile(window.innerWidth);
    return () => setMobile(window.innerWidth < 450);
  }, [window.innerWidth]); //ReferenceError: window is not defined

  return (
    <>
      <Header />
      <Component {...pageProps} />
      <Footer mobile={mobile} />
    </>
  );
};

export default LayoutContainer;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I would use window.matchMedia but instead, add an event listener in the useEffect and remove the window dependency, like this:

const { useState, useEffect } = React;

const Example = () => {
  const [isWide, setIsWide] = useState(null);

  useEffect(() => {
    const mql = window.matchMedia("(min-width: 768px)");
    const onChange = () => setIsWide(!!mql.matches);

    mql.addListener(onChange);
    setIsWide(mql.matches);

    return () => mql.removeListener(onChange);
  }, []);

  return <div>Is Wide: {isWide ? "true" : "false"}</div>;
};

ReactDOM.render(<Example />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

Inspired by https://github.com/streamich/react-use/blob/master/src/useMedia.ts

If you are looking to completely remove your useEffect, I supposed you could do something like this if you only need to find the width once on mount:

  let isMobile = null;
  
  if (typeof window !== "undefined") {
    isMobile = window.innerWidth < 450;
  }

  console.log(isMobile);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda