Blog/NotesConcept

Implement useClickOutside() custom Hook in React [Interview]

Understand the implementation of useClickOutside() custom hook in react and how it can be used to implement Modal like functionality.

Intermediate

Anuj Sharma

Last Updated Dec 23, 2025


Implement useClickOutside() custom Hook in React [Interview]

Detecting click outside a specific element is one of the common use-cases in the react development, and this functionality can be simplified using a reusable useClickOutside custom hook in react.

In this blog, we will go through the useClickOutside hook implementation and its real-life use-case.

Implementation of useClickOutside Custom Hook

Let's quickly jump into the implementation of react useClickOutside hook that detects clicks outside a specified element.

 import { useEffect } from 'react';

// Custom Hook
const useClickOutside = (ref, callback) => {
    const handleClick = (e) => {
        if (ref.current && !ref.current.contains(e.target)) {
            callback();
        }
    };

    useEffect(() => {
        document.addEventListener('click', handleClick);

        return () => {
            document.removeEventListener('click', handleClick);
        };
    }, [ref, callback]);
};

export default useClickOutside;

Real-life Example of Using useClickOutside Hook

The useClickOutside custom hook can be used to handle scenarios where you want to close a dropdown, modal, or any other component when the user clicks outside of it.

Let's consider a simple example where we have a modal component that should close when the user clicks outside of the modal.

useClickOutside Hook in a Modal component

import React, { useRef } from 'react';
import useClickOutside from './useClickOutside';

const Modal = ({ onClose }) => {
    const modalRef = useRef(null);

    // Close the modal when clicking outside of it
    useClickOutside(modalRef, onClose);

    return (
        <div style={styles.overlay}>
            <div style={styles.modal} ref={modalRef}>
                <h2>Example Modal</h2>
                <p>This modal closes when you click outside of it.</p>
                <button onClick={onClose}>Close</button>
            </div>
        </div>
    );
};

const styles = {
    overlay: {
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100vw',
        height: '100vh',
        backgroundColor: 'rgba(0,0,0,0.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    modal: {
        background: '#fff',
        padding: '20px',
        borderRadius: '8px',
        width: '300px',
        boxShadow: '0 0 10px rgba(0,0,0,0.3)',
    },
};

export default Modal;

Use modal component in the page

import React, { useState } from 'react';
import Modal from './Modal';

const App = () => {
    const [open, setOpen] = useState(false);

    return (
        <div>
            <button onClick={() => setOpen(true)}>Open Modal</button>
            {open && <Modal onClose={() => setOpen(false)} />}
        </div>
    );
};

export default App;

In this example, the Modal component will automatically close when the user clicks outside of it because of the usage of useClickOutside custom hook.

Conclusion

Not we have covered the implementation of useClickOutside custom hook in React to handle click events outside a specified element when working with components like modals, drop-downs, or popovers.

Understanding useClickOutside hook implementation will help you in react interview since this can be used in the implementation of multiple react component implementation questions.

Happy coding!

Further Learning

  1. Top 20 Most Asked Custom Hooks in React
  2. Best Resources to Ace React Interviews

Love this Blog? Share it Now!

Help others discover this resource

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀


Learn Next

Featured

100+ Top React JS Interview Questions And Answers

20 Most Asked Custom Hooks in React for InterviewsTop 10 React Performance Optimization Techniques25 Top JavaScript Interview Questions for BeginnersHow to create custom useInfiniteScroll Hook in ReactImplement useThrottle Custom Hook In React

Comments

Be the first to share your thoughts!

Guest User

Please login to comment

0 characters


No comments yet.

Start the conversation!

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀

Share your expertise

Publish a blog or quick notes on topics you know well — your write-up could be the answer someone needs before their next frontend interview.

Build your portfolio

Help the community

Sharpen your skills

Earn goodies

Other Related Blogs

React Hook Rules: Why hooks declarations are not allowed inside functions

Frontendgeek

Last Updated Feb 6, 2026

A quick guide to explain an important react interview question, why React Hooks declarations are not allowed inside functions or any conditional blocks with code example.

Implementing a stopwatch using React - Frontend Machine Coding Question

Pallavi Gupta

Last Updated Feb 21, 2026

Concise explanation of stopwatch implementation using React, it involves the usage of useEffect hook for creating a stopwatch and tracking milliseconds.

Best Frontend System Design Interview Cheat Sheet 📒

Anuj Sharma

Last Updated Jun 9, 2026

A Comprehensive Frontend System Design Cheat Sheet helps you approach the Frontend System Design Interview in the most structured way and covers the 7 most important Frontend System Design Topics.

Boost Your Site Speed with CSS Sprites: A Practical Guide

Vaibhav Kumar

Last Updated Jan 28, 2026

Master CSS sprites to slash HTTP requests, supercharge load times, and optimize icons—practical guide with code, tools, and 2026 best practices.

Stay Updated

Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

All in One Preparation Hub to Ace Frontend Interviews. Master JavaScript, React, System Design, and more with curated resources.

Consider Supporting this Free Platform

Buy Me a Coffee

Product

HomeFrontend InterviewFrontend JobsQuestionsNewInterview ExperienceBlogsToolsLeaderboardFrontendGeek Chrome extensionGet the extension on the Chrome Web Store →

© 2026 FrontendGeek. All rights reserved