local static variable using TNG-Hooks

I personally have prefered to use React Hooks over React, since the lifecycle functions were quite boring me and were the place where codes are mixed around each other.  I think the situation was quite far from ‘Reusability’ and made me to look for another solution. It was inevitable under the React’s convention then. And later, the React Team solved several problems with React Hooks.  I enjoyed them too like other fellow programmers. 


Recently I’ve rolled out shine bright Keyboard-Shortcut Handler based on Finite State Machine. Everything works as I designed. BUT when it turned to be failed to make clean and simple module(non-React component), I realized the class instance variable acts like global variable.  The instance variable has to be passed or referenced from/to related functions in any way.


Suddenly I came up the idea that I could use TNG-Hooks1 to make my functions act like Class whose local static variables !!!

import {TNG, useState} from "tng-hooks";
const drawMousePath = TNG(function(offsetX, offsetY){

   // previousX, previousY act like static varaible in this function!
   const [previousX, setX ] = useState(0);
   const [previousY, setY ] = useState(0);

   // do some works using these values
   console.log(previousX, previousY, offsetX, offsetY);

   // update
drawMousePath(1,2);  // 0, 0, 1, 2
drawMousePath(3,4);  // 1, 2, 3, 4
drawMousePath(5,6);  // 3, 4, 5, 6


Yes, the underline concept and fundamentals are well know by React Hooks.  But the thing is that we can elaborate a function to ‘class instance like’ one!

Not only each TNG-ed function has its own stack, but we can share ‘the stack’ between/among some functions if they are TNG-ed together. 

const [f1, f2, ...] = TNG(f1, f2, ...);


Isn’t it cool?? lol~


Even if you are using React Hooks, no problem at all to use TNG-Hooks together. Because you can rename useState (of TNG) to whatever you want. 

And also this pattern could be applied to the place where you want to hide class instance and give instance methods as API


My friends were excited when they were told this from me. Some were excited, some were unimpressed at all. But I believe that every one who knows React Hooks would be inspired by this idea for their own projects. Hope this helps you.




1 https://github.com/getify/TNG-Hooks