I have a situation where I have some values in stored local storage. I want to clear those values when the page loads for the first time. But, after that, if I want to set those values again,I should be able to do this and page refresh shouldn't remove this as well. So. the question is: are there any ways of doing something only on initial loads of the component and don't do anything afterwards.
CodePudding user response:
Yes, that is the typical use of sessionStorage
. It works the same way as localStroage
, but it will be clear after users closes browsers. However, between page reloads, it is preserved.
You can use it like this:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
const data = sessionStorage.getItem('key');
CodePudding user response:
You can create a count
variable and when react
app runs for the first time useEffect
will remove required items from localstorage
and will set count
to 1
in localstorage and then everytime component
re-renders it will check in localstorage
if count is 1 if it is 1 then it won't remove item from localstorage
.
useEffect(() => {
if(localStorage.getItem('count') !== '1') {
localStorage.removeItem('val')
localStorage.setItem('count', '1')
}
set()
}, [])
const set = () => {
localStorage.setItem('val', 'skndkj')
}