Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
6,667 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).