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

281
Visualizações
Make div appear only once after closing using useState and localstorage

I have a div with a close button. Currently, what it does is when the user clicks the close button, the div disappears. But when the user refreshes the page, the div is still there. I'm thinking of using localstorage but I'm confused as to how it should be incorporated when I am using useState. Here's my code.

const [isVisible, setIsVisible] = useState(true)
useEffect(() => {
      let hideDiv = localStorage.getItem('hideDiv ')
      if (!hideDiv ) {
        setIsVisible(true)
        localStorage.setItem('hideDiv ', 1)
      }
    }, [])
    if (!isVisible) return null

<div className="absolute right-5 text-gray flex text-white">
          <a href="#" onClick={() => setIsVisible(false)}>
            x
          </a>
        ... some text here ...
      </div>

My current idea is useEffect and localstorage, but considering how I'm completely new to React, I'm not so sure how I go about this as I've only tried hiding and showing elements using localstorage in Vanilla javascript

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

0

useEffect with an empty dependency array will fire once when the component mounts. This is a good place to get that value from local storage and set it to the state. Then your close function can just set the local storage to true.

I made a sandbox for you here: https://codesandbox.io/s/crazy-davinci-io03f?file=/src/App.js

You should probably initialise your state to false too. This will avoid that flicker that you see.

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