React's useState(...) Hook

Consider this line of code:

//Source: https://reactjs.org/docs/hooks-state.html
const [count, setCount] = useState(0);

How the heck does this work? I threw together a quick test which is shown below. Turns out, the parameter - 0 - is the initial state.  The second parameter coming out of useState is always the update/mutate method.

I really wish such documentation would present things like:

const initalState = 0;
const [count, setCount] = useState(initalState);

Why is count and setCount known or otherwise predictable values?

The first parameter, called p1 in my code example, is the current state. The second parameter is always the update method.

Consider this example where I added a call to invoke p2 with different data. First the code and then the console.

This serves as  means to handle a component's internal state. I'll be looking at how this is mixed in to a redux type system next but for now, I hope for this to be enough to help get others' over this hump.

Update regarding Redux

The redux system doesn't use useState in a basic configuration. You can mix and match them so you can have global state in redux and local state in the component whereas the latter would be using useState.

Frank Villasenor

Frank Villasenor

Owner and principal author of this site. Professional Engineering Lead, Software Engineer and Architect working from the Chicagoland area for healthcare SaaS company. Cert: AWS DevOps Professional
Chicago, IL