I have checked on blogs and other stack overflow questions for this. The answer is quite simple and clear, but doesn’t seem to work for me. I am using functional component, I tried to use both localStorage and sessionStorage for a simple counting app. The app still works but the count state defaults back to 0 on browser reload instead of the current state in the sessionStorage. I must be missing something or I get this completely wrong…
Here is my code…
Manipulating the count into and from the sessionStorage
// Setting the count to the stored value in localStorage...
useEffect(() => {
setCount(JSON.parse(sessionStorage.getItem('count')))
}, [])
// setting the local storage every time count changes...
useEffect(() => {
sessionStorage.setItem('count', count)
}, [count])
Handling click events…
// The handlers...
const plusHandler = () => {
const newCount = count
setCount(newCount + 1)
}
const minusHandler = () => {
const newCount = count
setCount(newCount - 1)
}
Printing the count using <p>{count}</p>
See the Full CodeSandbox Project Here
Even a short description of what I might be doing wrong will be appreciated…
>Solution :
Call sessionStorage.getItem() outside of useEffect to get the initial state of your counter synchronously:
const [count, setCount] = useState(parseInt(sessionStorage.getItem("count") || 0, 10))