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
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.