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

269
Visualizações
React: useLayoutEffect + useState running sync

I have been reading about this two hooks and try to find a workaround for my case now here but I cannot make it to work.

Basically, what I want to do is to render a certain amount of images if I am in desktop but less if I am in mobile (in this last case, I need a button to show the rest of the images)

So what did I do? started simply:

                    {images.slice(0, open ? images.length : 6).map(item => {
                        return (
                            <div}>
                                <Image
                                    src={whatever}
                                    alt={whatever}
                                />
                            </div>
                        );
                    })}

In this way, I can show every image or only 6 if mobile. Even the button, quite simple


                <Button
                    onClick={() => {
                        setOpen(!open);
                    }}
                >
                    {open ? (
                        <text>                         
                           close
                        </text>
                    ) : (
                        <text>                         
                           open
                        </text>
                    )}

now, what would be my initial state? well, that should depend on whats the width of the screen, right? okey, so this is how I solved it:

    const [size, setSize] = useState([0]);

    useLayoutEffect(() => {
        function updateSize() {
            setSize([window.innerWidth]);
        }
        window.addEventListener('resize', updateSize);
        updateSize();
        return () => window.removeEventListener('resize', updateSize);
    }, []);

perfect, now I have 'size' who tells me the width of the screen at any moment the user changes the layout. So now its when I am getting stuck: There is no way to initialize 'open' to true or false depending on if size is > || < than a certain width. If I do like this:

    const isMobile = size < breakpoints.tablet;
    const [open, setOpen] = useState(isMobile);

here for example, if I load the page on desktop, 'isMobile' is false, but 'open' is still true.

or

    const [open, setOpen] = useState(size < breakpoints.tablet);

but still, the value of 'isMobile' and 'open' are not sync. I guess because useLayoutEffect runs synchronously while useState async? In any case, how can I achieve having the 'open' variable having the correct initial state of 'isMobile'?

about 4 years ago · Juan Pablo Isaza
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