Unpacking how hooks work

I have heard some people struggling with the ‘magic’ around the new hooks API draft proposal so I thought I would attempt to unpack how the syntax proposal works at least on a superficial level.

The rules of hooks

There are two main usage rules the React core team stipulates you need to follow to use hooks which they outline in the hooks proposal documentation.

Don’t call Hooks inside loops, conditions, or nested functions

Only Call Hooks from React Functions

The latter I think is self evident. To attach behaviour to a functional component you need to be able to associate that behaviour with the component somehow.

The former however I think can be confusing as it might seem unnatural to program using an API like this and that is what I want to explore today.

State management in hooks is all about arrays

To get a clearer mental model, let’s have a look at what a simple implementation of the hooks API might look like.

Please note this is speculation and only one possible way of implementing the API to show how you might want to think about it. This is not necessarily how the API works internally.

How could we implement `useState()` ?

Let’s unpack an example here to demonstrate how an implementation of the state hook might work.

First let’s start with a component:

The idea behind the hooks API is that you can use a setter function returned as the second array item from the hook function and that setter will control state which is managed by the hook.

So what’s React going to do with this?

Let’s annotate how this might work internally within React. The following would work within the execution context for rendering a particular component. That means that the data stored here lives one level outside of the component being rendered. This state is not shared with other components but it is maintained in a scope that is accessible to subsequent rendering of the specific component.

1) Initialisation

Create two empty arrays: `setters` and `state`

Set a cursor to 0