DEV Community

Rafi
Rafi

Posted on

Creating useEffect in nodejs

React hooks is one of the best parts that I like about react. It would be nice to have something like that for node. So I came up with a really simple implementation of useEffect in node.

const useEffect = (callback, dependencies) => {
  // Calling it first time since there are no dependency
  if (dependencies === undefined) {
    return callback();
  }

  // Creating proxy for setters
  return new Proxy(dependencies, {
    set: function (target, key, value) {
      Reflect.set(target, key, value);
      callback();
    },
  });
};

module.exports = useEffect;
Enter fullscreen mode Exit fullscreen mode

you use it as follows

const readline = require('readline');
const useEffect = require('./useEffect');

// This has to be object because you can't create proxy of primitive types
const user = { input: '' };

let proxiedUser = useEffect(() => {
  if (proxiedUser.input && parseInt(proxiedUser.input, 10) % 2 === 0) {
    console.log(`${proxiedUser.input} is even`);
  } else {
    console.log(`${proxiedUser.input} is odd`);
  }
}, user);

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question('Enter number? ', (answer) => {
  proxiedUser.input = answer;
  rl.close();
});

Enter fullscreen mode Exit fullscreen mode

It essentially creates proxy of dependency and calls your callback when the dependency changes. This implementation could also be extended to handle multiple dependencies too.

On the downside with this implementation you can only use array or objects as dependencies but not simple primitives like numbers directly (you can use it by assign it as property of object like above). Since you can't create proxy of simple primitives like numbers yet.

Here is corresponding repo for the above source code.

Top comments (0)