Chapter 4 State

Chapter 4 discussion

Hello there!

Just going through the book (it’s great btw) and I am having trouble understanding what I believe is a pretty critical line (lol!):

const [selectedPostName, setSelectedPostName] = useState(‘Barry’);

I understand that the “selectedPostName” is the state variable which I am storing, and I understand that useState(‘Barry’) is the default value of the state variable.

What I am getting a bit lost on, is how setSelectedPostName (which I understand the is the function which updates my 'state variable) can be leveraged by anything (i.e. not just the Post.js component) without the function “body” being declared/specified/written out…

Is this done implicitly by the React Framework?

I hope that this question makes sense…

Thanks!

Hi,

Glad you are enjoying the book!

The setter function (in this case called setSelectedPostName) is created by React inside the useState function.
So useState is a function that when executed, creates (and returns) another function and the current state value.
Is that helpful?

Totally perfect… “implicitly created behind the scenes” == Magic!!!

Thanks so much, have a great weekend!

1 Like