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

207
Visualizações
how to rerender a page using UseEffect hook on window.innerWidth in react

I want to make some changes depending on the screen size

useEffect(() => {
        console.log("am called");

     if (window.innerWidth < 800) {
        document.getElementsByTagName("body")[0].style.display = "none";
     }
     if (window.innerWidth > 800) {
            document.getElementsByTagName("body")[0].style.display = "block";
        }

        
    }, [window.innerWidth]);

what is the problem with this code

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to observe window size changing and put this value to state.

    const [width, setWidth] = useState(0)
    useEffect(() => {
        const onResize = () => setWidth(window.innerWidth)
        window.addEventListener('resize', onResize);
        return () => {
            window.removeEventListener("resize", onResize)
        }
    }, [setWidth])

    //and then
    useEffect(() => {
        console.log("am called");

        if (width< 800) {
            document.getElementsByTagName("body")[0].style.display = "none";
        } else {
            document.getElementsByTagName("body")[0].style.display = "block";
        }


    }, [width]);

better solution

export default function useMatchMedia(condition) {
    const [isMatching, setIsMatching] = useState(false);

    useEffect(
        function updateMatchMedia() {
            if (!condition) return setIsMatching(true);

            const updateIsMatching = (event) => setIsMatching(event.matches);

            const matcher = window.matchMedia(condition);

            setIsMatching(matcher.matches);

            matcher.addEventListener('change', updateIsMatching);

            return () => {
                matcher.removeEventListener('change', updateIsMatching);
            };
        },
        [condition]
    );

    return [isMatching];
}

then you can use it

   isTablet = useMatchMedia(`(max-width: 800px)`);
   useEffect(() => {
     if(isTablet){
     } else {
     }
   }, [isTablet])
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