There is one thing I don't understand in this part from 'setState functional form' though:
functionCounter(){const[count,setCount]=useState(0)// Use a function to set Stateconstincrease=()=>setCount(()=>count+1)return(<><h1>Counter</h1><p>{count}</p><buttononClick={increase}className='btn'> + </button><buttononClick={()=>setCount(()=>count-1)}className='btn'> - </button></>)}
I don't understand why we'd use the functional update of setState without its count param: setCount(() => count - 1).
I would understand if we used the count param from setCount: setCount((count) => count - 1), to make sure we use the last count value
Your version is accurate. The point of using functional form is to ensure you get the most current state value and not the stale one (as in the original version).
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Thanks a lot that's very helpful!
There is one thing I don't understand in this part from 'setState functional form' though:
I don't understand why we'd use the functional update of setState without its count param:
setCount(() => count - 1)
.I would understand if we used the count param from setCount:
setCount((count) => count - 1)
, to make sure we use the lastcount
valueAm I missing something? :)
Your version is accurate. The point of using functional form is to ensure you get the most current state value and not the stale one (as in the original version).