How to make a custom hook for closing a modal when clicking outside(React, Typescript)

Samir Mirzaliyev
2 min readOct 19, 2022

Hi guys! Sometimes it’s not a better user experience to click the X button and close the modal screen as every developer knows. And it can be hard to implement especially if you don’t use any UI kit. So today I’ll explain how it is easy that with React and Typescript. Let’s get dive in.

First of all, we need to create a new custom hook for that which we can pass the callback function inside this hook. I’ll call that hook’s name useClickOutside, you can name what you want.

And useRef hook will help us in that case. So, we need to create a new reference object.

Now, we just need to write an event listener for the mouse-down action inside the useEffect hook. And this listener checks the reference every time. By the way, don’t forget to remove the listener on unmount.

Then we can use the hook. Just need to pass ref to our modal’s container and pass the onClose function to our hook. For example:

That’s it for this article. Thanks, guys, hope it will be helpful. If have any questions, be free to reach out to me.

--

--