Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

289
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda