In this article, we will learn how to create a very simple custom React hook. For simplicity sake, the only thing the hook will do is to show an alert message when a button is clicked.
In a nutshell, creating a custom hook is as simple creating a function, calling which returns something. This function, by convention, starts with use and we will call it useAlert.
|
|
The hook has to return something which can be a function, an array, an object, or even a primitive values. In our case, the hook will return a function. Let’s make our hook return the function.
|
|
That’s it! Really, we are done creating our first custom React hook. In unpredictable future wherever we need to alert Hello World!, we can use this marvelous hook. Let’s see how to use this hook in a component. We will create button our component which uses a function returned by our hook to alert the string.
|
|
We see how easy it is to create a hook.
It’s time to celebrate after all you have created a magical custom React hook. In our next article, we will create a more useful and reusable hook.
You can find the simple code used in this article on CodeSandbox.