Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!