Skip to content

Instantly share code, notes, and snippets.

@pH-7
Last active January 26, 2023 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pH-7/dbb7ffd1b3c1988dc9f5994e4b5ceb85 to your computer and use it in GitHub Desktop.
Save pH-7/dbb7ffd1b3c1988dc9f5994e4b5ceb85 to your computer and use it in GitHub Desktop.
Example of a React Counter with localStorage - https://www.youtube.com/@pH7Programming
import {useEffect, useState} from 'react'
import './App.css'
export const CounterApp = () => {
const storageKeyName = "count";
const retrieveCountValue = () => Number(localStorage.getItem(storageKeyName) || 0);
const [count, setCount] = useState(retrieveCountValue());
const addNumber = (count) => setCount(Number(count) + 1);
useEffect(() => {
localStorage.setItem(storageKeyName, String(count));
}, [count]);
return (
<div className="App">
Count Me
<button onClick={() => addNumber(count)}>
count is {count}
</button>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment