The useState Hook

There are a couple of core concepts with useState:

Use state in pure component.

Use any primitive (string/array/object etc.)

According to the docs they always return:

a reducer state an action dispatcher

However this can be simplified into a basic property value and a setter.

There is a simple rule which is very important to Hooks. That is that the Hooks are called at the top. That means outside of any conditionals or nesting blocks. This is crucial to the Hooks mechanism and we will examine why.

So let us expand out React engine to include the useState Hook. We will need a “state index” counter, as well as “state store” for values.

We have also added a useState method. It works by:

Checking if the current index has a value in the state, if not set the default

Then build the setter for the current state index value

Finally increment the index (for the next Hook) and return the setter and current value.

Now we will make use of our useState in our Component.

See the “count” and “name” usage above. Also we have utilised both inside the “inner” property so that we can spy on it in the terminal. Additionally we have added some manual methods to update the state values. They are manual as we are not worrying about the change detection or reconciliation in this post. We will be manually triggering the returned functions as well as the render method (following how we used it in our React engine section earlier).

So on running the below, we log the rendered output. We can see with each “click()” we are updating the count, and with “personArrived()” we are updating person (terminal output below line of code).

There is 1 main issue in our usage. That is that this would NOT work for many components at the same time. It is very tightly coupled to our single component. The state should be held in module scope or a single store namespaced to the component.