import React, {useState} from 'react' function HookCounterTwo () { const initialCount = 0 const [count, setCount] = useState(initialCount) return ( <div> Count: {count} <button onClick={() => setCount(initialCount)}>Reset</button> //This is not the best method because it is based upon whatever the initial Count is it doesn't access the previous state <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={() => setCount(count - 1)}>Decrement</button> //Best Method below <button onClick={() => setCount(prevCount => prevCount + 1)}>Increment</button> <button onClick={() => setCount(prevCount => prevCount - 1)}>Decrement</button> </div> ) } export default HookCounterTwo
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter