In my React app, when you refresh the browser I have to update / increment the count
value by 1
. Also I want to store this count
in localStorage.
How do I manage this?
As a start I have something like this:
const initialCount = () => {
if (typeof window !== 'undefined' && hasRedirectQueryParam) {
return Number(window.localStorage.getItem('count')) || 0;
}
return null;
};
const [count, setCount] = useState(initialCount);
useEffect(() => {
setCount(count);
window.localStorage.setItem('count', String(initialCount()));
}, []);
But how do I use setCount
now? So when the browser refresh count
increments by 1
?
What is a proper React implementation for this using React useState and useEffect hooks?
you should not use react state. just read the count from local stroage and update the value whenever the app launches (for example inside app.js file but outside the component).