How to Create Hooks In Javascript (Simple Examples)

Welcome to a tutorial on how to create hooks in Javascript. You may have heard of hooks from other tutorials, frameworks, or have already used them in other programming languages. But just what are hooks? How do we use and implement hooks in Javascript?

Hooks are usually used to intercept procedures, and possibly change the way they act. But hooks are not natively supported in Javascript, we can only simulate hooks using functions and events.

Just how is this done? Let us walk through some examples in this guide – Read on!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/hooks-in-javascript/” title=”How to Create Hooks In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

HOOK BASICS

Before we dive into any code, here is a section on the basics of hooks – What are hooks, what they do, and why we need them. Feel free to skip if you are already a code ninja.

 

WHAT IS A HOOK?

Let me just do a quick quote from Wikipedia:

In computer programming, the term hooking covers a range of techniques used to alter or augment the behaviour of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components.

Several other different geeky websites also offer a similar definition, but maybe a simple example will illustrate that better. Now, let us say that we have a generic function that will do an AJAX call to the server.

That will work, but it is not the most elegant solution. AJAX is asynchronous and runs in parallel. So what if the user clicks on the submit button multiple times? End up with multiple submissions? Also, there is no feedback on whether the AJAX process is successful or not. So here is where hooks come into play.

We can add a hook before the AJAX call to disable the submit button, to prevent the user from submitting multiple times. We can also add another hook after the AJAX call to show the results of the process, to re-enable the submit button.

 

 

WHY DO WE NEED HOOKS?

Now, some of you guys may be thinking – Isn’t that stupid? We could have just created a single simple function to do all of these. Why go through all the trouble to create so many functions, so much of all these roundabout useless hooks thing?

The keywords here are reusability, extendability, and flexibility. The AJAX function here is a common core process – We use it whenever we need to communicate with the server, and it could be shared among hundreds of other functions; We do not want to modify this core function, but to extend the usability of it, which is where hooks step in.

 

HOOKS, CALLBACK, EVENTS

Some of you advanced code ninjas may be a little confused right now – Isn’t the above example the same as a callback or event? Well yes, these 3 are relatives but totally different mechanics altogether:

  • Events are fired when certain things happen – Mouse click, keyboard press, finished loading, etc…
  • Callbacks are functions that we put into another function to complete a certain task.
  • Hooks intercept the process and may interrupt the normal process.

So before the hater-flamer Internet troll things start to throw smart-aleck comments – Javascript does not have a native hook implementation. The only “hook” that we can “build” in Javascript is achieved with events and/or callbacks. Also, the “interrupt normal process” part cannot be fully replicated in Javascript.

 

 

JAVASCRIPT HOOK EXAMPLES

Now that we are done with the basics, let us go into simple examples of how we can implement hooks in Javascript.

 

1) HOOKS USING FUNCTIONS

1a-hook-function.html
<p id="demoA"></p>

<script>
// (A) "HOOKED" AJAX FUNCTION
function doAJAX (url) {
  // (A1) BEFORE HOOK
  if (typeof before == "function") { before(); }
 
  // (A2) AJAX FETCH & AFTER HOOK
  fetch(url)
  .then(function (res) { return res.text(); })
  .then(function (txt) {
    if (typeof after == "function") { after(txt); }
  });
}
 
// (B) HOOKS
function before () {
  document.getElementById("demoA").style.color = "red";
}
function after (txt) {
  document.getElementById("demoA").innerHTML = txt;
}

// (C) GO!
doAJAX("x-dummy.html");
</script>

Yes, this is the “exact implementation” of the above example in the basics section.

  • function doAJAX() does an AJAX call to fetch some data from a specified URL.
  • Hooks are simulated using before() and after(). Altering what doAJAX() does before the AJAX call, and after the server responds.
  • I.E. We use if (typeof XYZ == "function") { XYZ(); } to check if before() and after() exists and call them accordingly.

 

 

2) HOOKS USING EVENTS

2-hook-event.html
<p id="demoB"></p>

<script>
// (A) "HOOKED" AJAX FETCH
function doAJAX (url) {
  // (A1) BEFORE HOOK
  var evt = new CustomEvent("before");
  window.dispatchEvent(evt);
 
  // (A2) AJAX FETCH & AFTER HOOK
  fetch(url)
  .then(function (res) { return res.text(); })
  .then(function (txt) {
    evt = new CustomEvent("after", { detail : txt });
    window.dispatchEvent(evt);
  });
}

// (B) HOOKS
window.addEventListener("before", function () {
  document.getElementById("demoB").style.color = "green";
});
window.addEventListener("after", function (evt) {
  document.getElementById("demoB").innerHTML = evt.detail;
});
 
// (C) GO!
doAJAX("x-dummy.html");
</script>

This should be self-explanatory – Instead of using functions, we dispatch custom events to simulate hooks here.

 

 

3) MULTIPLE HOOKS HANDLER

3-multi-hook.html
<p id="demoC"></p>

<script>
// (A) MULTIPLE HOOKS HANDLER
// credits : https://jsbin.com/joxigabeyi/edit?js,console
var hooks = {
  // (A1) CURRENT HOOK QUEUE
  queue : {},

  // (A2) ADD FUNCTION TO QUEUE
  // name : name of function to add hook to
  // fn : function to call
  add : function (name, fn) {
    if (!hooks.queue[name]) { hooks.queue[name] = []; }
    hooks.queue[name].push(fn);
  },

  // (A3) CALL A HOOK
  // name : name of function to add hook to
  // params : parameters
  call : function (name, ...params) {
    if (hooks.queue[name]) {
      hooks.queue[name].forEach(function (fn) { fn(...params); });
      delete hooks.queue[name];
    }
  }
};

// (B) "HOOKED" AJAX FETCH
function doAJAX (url) {
  // (B1) BEFORE HOOK
  hooks.call("before");
 
  // (B2) AJAX FETCH & AFTER HOOK
  fetch(url)
  .then(function (res) { return res.text(); })
  .then(function (txt) {
    hooks.call("after", txt);
  });
}

// (C) HOOKS
hooks.add("before", function () {
  document.getElementById("demoC").style.color = "blue";
});
hooks.add("before", function () {
  document.getElementById("demoC").style.background = "lightblue";
});
hooks.add("after", function (res) {
  document.getElementById("demoC").innerHTML = res;
});
hooks.add("after", function () {
  document.getElementById("demoC").innerHTML += "FOO BAR!";
});

// (D) GO!
doAJAX("x-dummy.html");
</script>

Credits go to this hook snippet on JSBIN. In this final so-called “advanced example”, we address one issue with the above simple examples – What if we want to run more than one hook?

  • We introduce a var hooks hook handler.
  • Basically, we use hooks.add() to store hooks functions into hooks.queue.
  • Use hooks.call() to run the respective hooks.

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the code, and here is a small extra that may be useful to you.

 

ARROW FUNCTIONS

I can feel the angry “master coder troll things”. This is so dumb! You should be using arrow functions! Yes – I know what arrow functions are. I deliberately didn’t use them to keep this tutorial “newbie friendly”. For those who are curious:

  • The “common function” – function twice (n) { return n * 2; }
  • We can also do it this way – var twice = function (n) { return n * 2; }
  • Shorthand it using an “arrow function” – var twice = (n) => { return n * 2; }
  • For a single parameter, we can omit the round brackets – var twice = n => { return n * 2; }
  • For a single line return function, we can totally omit the curly brackets and return too – var twice = n => n * 2;

Go ahead and try it for yourself.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

How To Create Hooks In Javascript (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand hooks, and improve your project. If you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “How to Create Hooks In Javascript (Simple Examples)”

  1. Hi, thank you for this example, it was straight-forward and concise. I had two questions:
    1. Would a Set work better for the hooks rather than an Array? Or is it a wash?
    2. Why are you deleting the hooks entry after the function call?

    1. 1) Don’t quite catch what you mean. But hooks.queue is an object of arrays.

      2) No right-or-wrong here, but think in the opposite direction too. Why and when do you want to keep them? Running the same set of hooks for 2 different processes makes no sense. But if it is a repeated process – The same set of hooks make sense.

Leave a Comment

Your email address will not be published. Required fields are marked *