This page looks best with JavaScript enabled

Our First Custom React Hook

 ·  ☕ 2 min read

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.

1
2
3
    const useAlert = () => {
        // return something
    }

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.

1
2
3
4
5
    const useAlert = () => {
        return () => {
            alert('Hello World!')
        }
    }

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.

1
2
3
4
5
    const App = () => {
        const sayHelloWorld = useAlert(); 
        //since the function returned by our hook was unnamed, we can call it anything we want. We will call it `sayHelloWorld`
        return <button onClick={sayHelloWorld}>Click me!</button>;
    };

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.

Share on

Muhammad Kashif Nazar
WRITTEN BY
Muhammad Kashif Nazar
Senior Software Engineer