//store the count in the localStorage // get the value from localStorage and set initial value to the count
// Solution one: JSON.parse will be called every single render
const [count, setCount] = useState(JSON.parse(localStorage.getItem("count")));
useEffect(() => {
localStorage.setItem("count", JSON.stringify(count));
}, [count]);
// Solution 2: initializer function of useState
const [count, setCount] = useState(() =>
JSON.parse(localStorage.getItem("count"))
);
useEffect(() => {
localStorage.setItem("count", JSON.stringify(count));
}, [count]);
My question: How come solution 2 will prevent code from calling JSON.parse every render?
Thanks