// imagine props and state is the same
// as this.props and this.state
var props = { }
var state = { counter: 0 }
/* Our fake implementation of react setState */
var setStatesToRun = []
function setState(myFunction){
setStatesToRun.push(myFunction);
}
/* Our fake implementation of react batch update */
function batchRunStateUpdates() {
propsLocal = props
stateLocal = state
f1 = setStatesToRun.shift() // get setState to run
newState = f1(stateLocal, propsLocal)
console.log("Local state")
console.log(newState) // newState: { counter: 3 }
console.log("Global state")
console.log(state) // state: { counter: 0 }
f2 = setStatesToRun.shift()
newState = f2(newState, propsLocal)
console.log("Local state")
console.log(newState) // newState: { counter: 2 }
console.log("Global state")
console.log(state) // state: { counter: 0 }
// ... get the next setState function
// This whole block should be a loop, but it is this way
// to make the example easier to understand
console.log("Will update global state")
state = newState
console.log("Global State")
console.log(state) // state: { counter: 2 } // WRONG!!
}
console.log("setStatesToRun")
console.log(setStatesToRun)
// Right
setState((prevState, props) => {
console.log("Will run increment by 3")
return {
counter: prevState.counter + 3
}
});
// Wrong, we will use the state
setState((prevState, props) => {
console.log("Will run increment by 2");
return {
counter: state.counter + 2
// replace with prevState.counter + 2 to make it work
}
});
console.log("setStatesToRun")
console.log(setStatesToRun)
batchRunStateUpdates();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.