391

I recently heard the term "hook" while talking to some people about a program I was writing. I'm unsure exactly what this term implies although I inferred from the conversation that a hook is a type of function. I searched for a definition but was unable to find a good answer. Would someone be able to give me an idea of what this term generally means and perhaps a small example to illustrate the definition?

4
  • 12
    See Hooking @ Wikipedia. The link is buried in one of the lower-voted answers.
    – Palec
    Commented Jul 5, 2014 at 18:25
  • 2
    Events and hooks look similar. So is there any difference? If event callbacks are called only after an event occurs (e.g. click), there's the onbeforeunload event. That seems like the callback will be called before the actual event. So is it technically a hook disguised an event? Are hook handlers called before, instead, or after the main operation? ... I believe there are several differences between a hook and an event. A hook looks like a low-level intervention, and an event is like a restricted version of a hook. Why is no one talking about this? Someone enlighten us.
    – akinuri
    Commented Apr 25, 2021 at 12:39
  • @akinuri your thoughts are good, but the thing is that 'hooks" is "something" in programming, so in general a function, that is called after a certain "event" happened. The thing is that an "event" can be something another function or another callback, called by another hook, or a browser event as a click or a keypress etc. So Hooks describe this "process" Commented Oct 11, 2021 at 13:55
  • Hook methods are a vital part of the Template Method Pattern Commented Sep 8, 2023 at 16:24

16 Answers 16

209

Essentially it's a place in code that allows you to tap in to a module to either provide different behavior or to react when something happens.

7
  • 16
    Is this similar to a callback?
    – Chris
    Commented Jan 22, 2009 at 0:05
  • 30
    Hooks often (but not always) use callback functions. For example, you might hook an event system using "hookEvent(Events.STARTUP, myCallbackFunction)". You are passing a function pointer to the hookEvent function, so it knows what function to call when the event occurs. Hope that helps :-) Commented Jan 22, 2009 at 0:12
  • 10
    exactly. A callback is a "type" of hook.
    – Micah
    Commented Jan 22, 2009 at 1:33
  • 29
    um ... no. A callback is a callback and has nothing to do with hooks, callbacks are simply USED for the IMPLEMENTATION of hook-methods. Callbacks are pointers (RELJMP) to functions/methods/procedures (CALL), hooks are modifications to running applications.
    – specializt
    Commented Oct 27, 2014 at 14:31
  • 1
    @SahilBabbar No. An interrupt causes the instructions at some specified place (the interrupt) to be executed. You may be able to hook into the interrupt handling process though, for example by modifiying the table listing the locations of the interrupt handlers so that your code gets called first on interrupt (and then your code would call the previously present interrupt handling code, in a daisy-chain manner) Commented Dec 16, 2016 at 1:51
108

A hook is functionality provided by software for users of that software to have their own code called under certain circumstances. That code can augment or replace the current code.

In the olden days when computers were truly personal and viruses were less prevalent (I'm talking the '80's), it was as simple as patching the operating system software itself to call your code. I remember writing an extension to the Applesoft BASIC language on the Apple II which simply hooked my code into the BASIC interpreter by injecting a call to my code before any of the line was processed.

Some computers had pre-designed hooks, one example being the I/O stream on the Apple II. It used such a hook to inject the whole disk sub-system (Apple II ROMs were originally built in the days where cassettes were the primary storage medium for PCs). You controlled the disks by printing the ASCII code 4 (CTRL-D) followed by the command you wanted to execute then a CR, and it was intercepted by the disk sub-system, which had hooked itself into the Apple ROM print routines.

So for example, the lines:

PRINT CHR(4);"CATALOG"
PRINT CHR(4);"IN#6"

would list the disk contents then re-initialize the machine. This allowed such tricks as protecting your BASIC programs by setting the first line as:

123 REM XIN#6

then using POKE to insert the CTRL-D character in where the X was. Then, anyone trying to list your source would send the re-initialize sequence through the output routines where the disk sub-system would detect it.

That's often the sort of trickery we had to resort to, to get the behavior we wanted.

Nowadays, with the operating system more secure, it provides facilities for hooks itself, since you're no longer supposed to modify the operating system "in-flight" or on the disk.

They've been around for a long time. Mainframes had them (called exits) and a great deal of mainframe software uses those facilities even now. For example, the free source code control system that comes with z/OS (called SCLM) allows you to entirely replace the security subsystem by simply placing your own code in the exit.

0
69

In a generic sense, a "hook" is something that will let you, a programmer, view and/or interact with and/or change something that's already going on in a system/program.

For example, the Drupal CMS provides developers with hooks that let them take additional action after a "content node" is created. If a developer doesn't implement a hook, the node is created per normal. If a developer implements a hook, they can have some additional code run whenever a node is created. This code could do anything, including rolling back and/or altering the original action. It could also do something unrelated to the node creation entirely.

A callback could be thought of as a specific kind of hook. By implementing callback functionality into a system, that system is letting you call some additional code after an action has completed. However, hooking (as a generic term) is not limited to callbacks.

Another example. Sometimes Web Developers will refer to class names and/or IDs on elements as hooks. That's because by placing the ID/class name on an element, they can then use Javascript to modify that element, or "hook in" to the page document. (this is stretching the meaning, but it is commonly used and worth mentioning)

1
  • What do you mean by "hook in to the page document"? Could you give an example? I understood the first example - giving an html element an id so you can use javacript to modify the element. Commented Sep 26, 2018 at 15:46
58

Simple said:

A hook is a means of executing custom code (function) either before, after, or instead of existing code. For example, a function may be written to "hook" into the login process in order to execute a Captcha function before continuing on to the normal login process.

1
  • Thank you. Do you also have a such simple explanation for callback functions?
    – Xfce4
    Commented Apr 14, 2022 at 14:01
30

Hooks are a category of function that allows base code to call extension code. This can be useful in situations in which a core developer wants to offer extensibility without exposing their code.

One usage of hooks is in video game mod development. A game may not allow mod developers to extend base functionality, but hooks can be added by core mod library developers. With these hooks, independent developers can have their custom code called upon any desired event, such as game loading, inventory updates, entity interactions, etc.

A common method of implementation is to give a function an empty list of callbacks, then expose the ability to extend the list of callbacks. The base code will always call the function at the same and proper time but, with an empty callback list, the function does nothing. This is by design.

A third party, then, has the opportunity to write additional code and add their new callback to the hook's callback list. With nothing more than a reference of available hooks, they have extended functionality at minimal risk to the base system.

Hooks don't allow developers to do anything that can't be done with other structures and interfaces. They are a choice to be made with consideration to the task and users (third-party developers).

For clarification: a hook allows the extension and may be implemented using callbacks. Callbacks are generally nothing more than a function pointer; the computed address of a function. There appears to be confusion in other answers/comments.

21

Hooking in programming is a technique employing so-called hooks to make a chain of procedures as an event handler.

6

Hook denotes a place in the code where you dispatch an event of certain type, and if this event was registered before with a proper function to call back, then it would be handled by this registered function, otherwise nothing happens.

3

hooks can be executed when some condition is encountered. e.g. some variable changes or some action is called or some event happens. hooks can enter in the process and change things or react upon changes.

2

Oftentimes hooking refers to Win32 message hooking or the Linux/OSX equivalents, but more generically hooking is simply notifying another object/window/program/etc that you want to be notified when a specified action happens. For instance: Having all windows on the system notify you as they are about to close.

As a general rule, hooking is somewhat hazardous since doing it without understanding how it affects the system can lead to instability or at the very leas unexpected behaviour. It can also be VERY useful in certain circumstances, thought. For instance: FRAPS uses it to determine which windows it should show it's FPS counter on.

2

A chain of hooks is a set of functions in which each function calls the next. What is significant about a chain of hooks is that a programmer can add another function to the chain at run time. One way to do this is to look for a known location where the address of the first function in a chain is kept. You then save the value of that function pointer and overwrite the value at the initial address with the address of the function you wish to insert into the hook chain. The function then gets called, does its business and calls the next function in the chain (unless you decide otherwise). Naturally, there are a number of other ways to create a chain of hooks, from writing directly to memory to using the metaprogramming facilities of languages like Ruby or Python.

An example of a chain of hooks is the way that an MS Windows application processes messages. Each function in the processing chain either processes a message or sends it to the next function in the chain.

2

In the Drupal content management system, 'hook' has a relatively specific meaning. When an internal event occurs (like content creation or user login, for example), modules can respond to the event by implementing a special "hook" function. This is done via naming convention -- [your-plugin-name]_user_login() for the User Login event, for example.

Because of this convention, the underlying events are referred to as "hooks" and appear with names like "hook_user_login" and "hook_user_authenticate()" in Drupal's API documentation.

2
  • This follows the idea mentioned above, of a "callback" "to react when something happens". In this case, the callback is not explicitly registered, but based on "magic naming". This is currently discussed on drupal.org, see Use Symfony EventDispatcher for event hooks
    – donquixote
    Commented May 24, 2012 at 7:39
  • To generalize, a hook/callback/listener can be "made known to the calling code" in different ways (not saying this is complete): 1. magic-named functions 2. magic-named classes 3. explicitly registered functions 4. explicitly registered objects (listeners, subscribers, observers) 5. explicitly registered class names (+ optional constructor args), to be instantiated before the hook fires. 6. by modifying the calling code
    – donquixote
    Commented May 24, 2012 at 7:39
2

In VERY short, you can change the code of an API call such as MessageBox to where it does a different function edited by you (globally will work system wide, locally will work process wide).

2

Many answers, but no examples, so adding a dummy one: the following complicated_func offers two hooks to modify its behavior

from typing import List, Callable


def complicated_func(
    lst: List[int], hook_modify_element: Callable[[int], int], hook_if_negative=None
) -> int:
    res = sum(hook_modify_element(x) for x in lst)
    if res < 0 and hook_if_negative is not None:
        print("Returning negative hook")
        return hook_if_negative
    return res


def my_hook_func(x: int) -> int:
    return x * 2


if __name__ == "__main__":
    res = complicated_func(
        lst=[1, 2, -10, 4],
        hook_modify_element=my_hook_func,
        hook_if_negative=0,
    )
    print(res)
2

A function that allows you to supply another function rather than merely a value as an argument, in essence extending it.

0

I think it's time for us programmers to have a well-defined terminology that is unambiguous, so let me try to define hooks, and compare them to callbacks and event listeners to that end.

Unless there is one authoritative entity that came up with a concept and declared that "X shall mean Y", I think the next best thing to do is try and aggregate how each individual sees a concept and highlight the common ground.

Hooks vs. Event Listeners vs. Callbacks

Hooks are functions that are invoked when a certain step occurs. It should naturally imply that there are well-defined steps in the function that invokes the hooks, or well-defined states if those hooks are attached to a state machine.

This makes hooks look similar to event listeners; however, the difference that distinguishes an event listener from a hook should be that it's not invoked in terms of a progress or a state change. A button can be tapped zero or more times, and it is invoked every time the button is tapped. It's not invoked when the button changes its state from enabled to disabled for instance. They are merely responders to plain events.

Callbacks should be all about returning and resuming control. When we make a function call that does some I/O, we use callbacks to resume the program where it left off. As such, functions that take a callback parameter are naturally amenable to changing them into functions that return a promise--i.e. async functions.

Litmus test

If you are familiar with Kotlin coroutine parlance,

  • Hooks can easily be made into flows. They can either emit events such as OnStarted or emit states Started.
  • Event listeners should just remain as plain functions. If you must force them to become flows, they will probably be flows that emit a Unit. You may choose to emit a changing value such as Date, but whatever the value is, it's not indicative of the state/step of the program.
  • Callbacks can be gutted and laid out after the function that originally took the callback as its parameter. While doing that, the function that used to require the callback can be changed to a suspend function--or one that returns a Deferred.
0

What is meant by the term "hook" in programming?

A really good answer to this question requires detailed specification of the entire context associated with the term "programming". There will be as many different correct answers about the meaning of this term as there are different programming languages, operating systems, hardware platforms, software packages, libraries, programs exposing interfaces and so on.

In other words this question is too broad to be answered considering every possible use case.

This said let's approach the impossible and give a view on it from the perspective of writing program code.

Writing a program code text is nothing else as using by the programming language environment pre-defined words/symbols/terms/variables/functions/methods/objects/constants/expressions/operators/... to arrange them according to the programming language rules to a code which can be executed/run.

So a hook will be nothing else as only one of such words/symbols/terms used in the text of your code. What makes a hook then to be a hook and not a callback function or an event listener?

Let's give an example of customizing the behavior of one of the oldest text editing applications Emacs which can be programmed using the elisp dialect of the Lisp programming language:

(add-hook 'window-buffer-change-functions
  `(lambda (&optional window &rest rest)
     (setq frame-title-format ;; #1b. Set the OS-window title: 
       '(:eval (concat "Neo@oOo Emacs :      " (current-buffer-filename-or-the-buffer-name))))
   [ ... and so on ... ]

In this example add-hook is an by the Emacs executable environment pre-defined helper function. This helper function is used to achieve executing of the self-written lambda function any time the user changes the buffer shown in an Emacs window and needs as parameter a pre-defined symbol window-buffer-change-functions to provide the desired specific functionality.

The helper function called add-hook is a hint that there is a hook involved here.

Now you are free to decide yourself whether add-hook suggests that the hook is the lambda function added to window-buffer-change-functions or the hook is the term/symbol/variable/name window-buffer-change-functions becoming added the function lambda.


For the sake of completeness as a kind of a summary of all the up to now given other answers the in my eyes most helpful sometimes extremely shortened, sometimes a bit re-phrased excerpts:

A function that allows you to pass any number of another functions rather than values as arguments/parameter is the essence of what a hook is.

Hooks are a category of functions that allow the base code to call extension code.

A hook is what allows executing custom code (function) either before, after, or instead of already existing core code.

A hook is a functionality provided by a software for users of that software making it possible to execute their own code under certain during execution of the software occurring circumstances.

In the Drupal content management system the term 'hook' is used as prefix of API functions exposing underlying events as for example: "hook_user_login", "hook_user_authenticate()".

Not the answer you're looking for? Browse other questions tagged or ask your own question.