DEV Community

How to pass state between components in reactjs

Zeyad Etman on July 25, 2018

In this post, i'll explain how to pass a state between components in Reactjs. We'll build a small 'How many books did you read?' app, in this appli...
Collapse
 
uranium93 profile image
uranium93

salem
nice explanation but it's not recommended to use :
this.setState({status: !this.state.status}, this.updateLibraryCount);
|.|
|_|
V
this.setState({status: !this.state.status} you better use

this.setState((prevState) => {
return { status: !prevState.status }
})

Collapse
 
zeyadetman profile image
Zeyad Etman

Why?

Collapse
 
chiangs profile image
Stephen Chiang

setState happens asynchronously... Therefore you need to use previous state first to ensure you are using the latest if you are going to calculate the state based on previous state.

Thread Thread
 
uranium93 profile image
uranium93

Yes this is it
Thank you

Collapse
 
keabard profile image
Thomas Simonnet • Edited

Hello Zeyad,

thanks for this state tutorial!

I was asking myself several questions while reading it though. I hope you can enlighten me :)

  • Why do you keep the book ID in the <Book> component state ? Wouldn't it be prettier to pass the book.id prop when you call this.props.handleCounter in updateLibraryCount? To me, the ID should not be modified, so we don't have to put it in the state.

  • Is there any particular reason why you don't pass a function as the first argument of this?

    this.setState({status: !this.state.status}, this.updateLibraryCount);

Thanks again!

See you :)

Collapse
 
zeyadetman profile image
Zeyad Etman • Edited

Thanks Thomas, to your first question, you're right it'll be prettier, you're welcome to contribute and update this on GitHub repo.
To your second question, from Reactjs documentation

"The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered."

and this what i want.

Collapse
 
keabard profile image
Thomas Simonnet

I was talking about the first parameter :)