Skip to content

Instantly share code, notes, and snippets.

@jogilvyt
Created January 19, 2021 15:53
Show Gist options
  • Save jogilvyt/dc6e6f6328e03473831e2791771a5edf to your computer and use it in GitHub Desktop.
Save jogilvyt/dc6e6f6328e03473831e2791771a5edf to your computer and use it in GitHub Desktop.
A React counter app with localStorage
import { useState, useEffect } from "react";
function App() {
const key = "count";
const [count, setCount] = useState(() => {
const persistedValue = window.localStorage.getItem(key);
return persistedValue !== null ? JSON.parse(persistedValue) : 0;
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(count));
}, [count]);
return (
<div>
<h1>Counter</h1>
<p>Number: {count}</p>
<button onClick={() => setCount(count - 1)}>-1</button>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment