JavaScript is single threaded, if someone clears the global before calling our hook function, we will write in a fresh global and nobody can do something while our function runs as long as we only make synchronous calls.

React calls our functional component so it has control over what happens before and after that call.

Hooks Example

Below, I’ve tried to write a simple example that illustrates how we could implement the "magic" of hooks. This has nothing to do with the official React implementation, but rather, it shows how the idea works.

It tries to get its state from the last run from the globalHooks variable. This is a Map object set by our run function before our component function is called. Either it has data from the last run, or we need to create our own hookData.

The hookData.store array is used to store the values from last calls and the hookData.calls value is used to keep track of how much this function has been called by our component.

With hookData.store[hookData.calls] we can grab the last value stored by this call; if it doesn't exist we have to use the defaultValue.

The setValue callback is used to update our value, for example when clicking a button. It gets a reference to calls so it knows to which call of the setState function it belongs. It then uses the hookData.render callback, supplied by the render function, to initiate a re-render of all components.

The hookData.calls counter is incremented.

The hookData is stored in the globalHooks variable, so it can be used by the render function after the component function returned.

Conclusion

While the approach I took for implementation is far away from the actual React implementation, I think it demonstrates that hooks aren't crazy dev magic, but a smart way to use JavaScript constraints, that you could implement yourself.

My First Book

If you liked this explanation and want to learn React, you may be interested in my first book:

If you like understanding how React works by taking it apart, then you might like my book React From Zero. In the book, I dissect how React works by examining how components work, how elements are rendered, and how to create your own Virtual DOM.