I am trying to show the text "Hello" only on first load. If user close window and opens again then it should show again. But while in the window and navigating to page should not show the "Hello".
Scenario:
- Enter url: /hello
- Show "Hello"
- Enter url: /bye
- Enter url: /hello
- Don't show "Hello"
- Close window
- Open window
- Enter url: /hello
- Show "Hello"
What I am trying it withe unload
event:
const firsttime = localStorage.getItem('firsttime')
useEffect(() => {
window.addEventListener('unload', () => {
localStorage.removeItem('firsttime')
})
const t = setTimeout(() => {
localStorage.setItem('firsttime','1')
},2000)
return () => {
clearTimeout(t)
window.removeEventListener('unload', null)
}
},[firsttime])
return !firsttime && "Hello" || null
This is working fine when I navigate to the pages, the "Hello" is shown for the first time and after that it is not being shown. But when I directly enter the url (it gets refreshed), the "Hello" is shown. I don't want to show the "Hello" on any refresh. I only want to show it if the window is closed and opened again. So, how can I detect the window is opened for the first time and also after closing it.