Last active
January 26, 2023 02:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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