In my React app I set my localStorage item count
with a value of 1
.
useEffect(() => {
window.localStorage.setItem('count', String(1));
}, []);
How do I increment this localStorage value by 1
, on every page refresh?
In my React app I set my localStorage item count
with a value of 1
.
useEffect(() => {
window.localStorage.setItem('count', String(1));
}, []);
How do I increment this localStorage value by 1
, on every page refresh?
2
Answers
Before setting the value in localStorage, check if value already exists and increment if exists otherwise set to 1.
Ref – https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
To increment the value of the
count
item inlocalStorage
; you can use the following code inside your useEffect:CODE SAMPLE
NOTE:
You can also notice that page refresh count is incremented by 2 in development because of new
React18
feature1.Docs Reference