I have the following reactjs code:
import React, { useState, useEffect } from 'react'
const Test = () => {
const [counter, setCounter] = useState(0)
useEffect(() => {
const data = localStorage.getItem('counter')
setCounter(parseInt(data, 10))
console.log('init', data)
}, [])
useEffect(() => {
localStorage.setItem('counter', counter)
console.log('changed', counter)
}, [counter])
const addCounter = () => {
setCounter((c) => c + 1)
console.log('added', counter)
}
return (
<div>
{counter}
<button onClick={addCounter}>+</button>
</div>
)
}
function App() {
return (
<div className='App'>
<Test />
</div>
)
}
The useEffect() hooks are being called multiple times. The states are persisted in localStorage. But upon page refresh, the states reset to default values:
init 4 <--- counter was incremented to 4 at previous session
changed 0 <-- counter is reset to 0??
init 0 <-- this should not appear
changed 0
What am I doing wrong?
useEffect()is being called multiple times is probably because you haveStrictModeon. Go to yourindex.jsand remove theStrictModetags.StrictModerenders components multiple times for debugging purposes.StrictModeand it's working now. Thanks