UseState Example Previous State
Tue Sep 06 2022 17:42:12 GMT+0000 (Coordinated Universal Time)
Saved by
@bfpulliam
#react.js
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
content_copyCOPY
PreviousCount is a function that takes in the current value and then increases it by 1.
Comments