JavaScript React Basics Understanding State Update State Based on Previous State

Joseph Butterfield
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Butterfield
Full Stack JavaScript Techdegree Graduate 16,430 Points

How does prevState reference this.state before change?

I think I have analyzed this correctly, but I want to be sure...

So once Guil changes the function from a direct reference to the Class state, TO a callback function, how is the parameter passed into the callback function referencing the class's initial state without "this.state.score"? prevState just seems an arbitrary parameter, but how does it reference the previous state (NOT this.state)?

--Method references Class state directly

incrementScore = () => { this.setState({ score: prevState.score + 1 }); } --> this.setState( {/* Object with updated state */ } )

--Method uses callback function to reference previous state

incrementScore = () => { this.setState( prevState => ({ score: prevState.score + 1 })); }

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous React Docs specify a callback function, in which two parameters are passed to reference the props and previous state as follows:

this.setState( (state, props) => { stateName: state.stateName + 1 } )

So are we saying that we can simply omit the extended React setState() param "props" and use the arbitrary prevState as the "state" param? If so, does React default a single parameter to the "state" parameter, and we have to declare (state, props) to actually read the "props" parameter, if we choose to do so? Example:

this.setState( state => { score: state.score + 1 } )

This is the only sensible thing to me similar to last unit's Express .get() and .use() callbacks which contain the (res, req, next) parameters, regardless of whether res.method(), req.method(), "next" param, or even "err" param are actually used within the callback.

1 Answer

Sean Paulson
Sean Paulson
5,403 Points

Yes in JS if you have a CB function that takes cb(param1, param2, param3) you can just pass cb(p1, p2) Unless of course its a required param. usually it will say in the docs if it is required. What you cant do is skip a param cb(p1, p3).