DEV Community

Rafi
Rafi

Posted on

3 1

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more