In my React app, when you refresh the browser I have to update 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?
2
Answers
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).
I think this is what you want. You can define the initialCount function as shown below so that it can be hoisted. You should add the number in the dependency array so that the newest value will be persisted in the local storage.