I am reading Redux tutorial and in a code snipped there is ‘prevCounter’ variable used without being initialized – ‘()’ has no param within it. How is it possible that prevCounter can be used within setCounter call? Is prevCounter by default initialized with counter state thanks to arrow syntax used when calling setCounter and incremented prevCounter is implicitly returned?
Here is the snippet:
function Counter() { // State: a counter value const [counter, setCounter] = useState(0) // Action: code that causes an update to the state when something happens const increment = () => { setCounter(prevCounter => prevCounter + 1) } // View: the UI definition return ( <div> Value: {counter} <button onClick={increment}>Increment</button> </div> ) }
URL to the tutorial: https://redux.js.org/tutorials/essentials/part-1-overview-concepts
Advertisement
Answer
The following code prevCounter => prevCounter + 1
is an Arrow Function. That means that when the function increment
(has no paramter) is called, it will trigger the setCounter
function with a callback function (the arrow function above). This callback function takes the parameter prevCounter
, adds one to it and returns the value. Internally the setCounter
function stores somehow the current value and the value will be passed as the parameter prevCounter
to the callback function every time setCounter
is called.