This weekend I came around a very interesting talk by Max Gallo where he shows two pieces of code: one using Mobx and the other one using RxJS. During the talk, he comments out the specific imports from the libraries and implements its own version that matches the API and works.
This really inspired me to do something similar with the fresh new React hooks. I decided I could write one function with this shiny new additions and then implement myself.
I’m quite happy with the result but I would encourage NO ONE to use this implementation. I am really happy because, by coding it, I started to realize the importance of what is going on with hooks and why they are revolutionary in their own way. Also, once you do something like this, you start to understand some rules like “don’t make conditional useHook calls”.
In order to spend less than a couple of hours playing with it, I decided to implement just the useState
hook instead of something more generic (or more tied to React like useEffect
and it’s relationship with component lifecycle). On a side note, React’s useState
implementation uses useReducer
internally, and mine does not.
So here is the code:
The code is divided into three main parts. The first part is the implementation of useState
, which I will dive a bit more in a bit. The second part defines two “components” (functions which in the case just return an api). I’m saying they are components because this is not hooked into React, so I’m just returning an api object. In a real React application, that object would not exist, and the functions would be called when clicking an element or something. The third consists of invoking these functions and playing with asynchronous calls.
The useState
implementation is pretty straightforward. Basically, I keep the previous call of useState
from a particular component and, from there, I can define the particular behavior of the returned value
and setValue
. The values are just stored in a simple array per component, and the amount of useState
calls per component are stored per component, too. I have a little helper renderFn
which just resets some values (that could be handled by the rendering library itself, but this example is a dummy).
Functions (or “components”) just use the hook twice, to console.log
the current state and to modify the songs later on.
The third part is just setting some timeouts after which songs get set, in order to see how the solution works not only in synchronous situations (after each setSong
the functions get called again and the console.log
calls are triggered.
Hope you like the approach and hope it eventually inspires some of you to do something similar.