{"size": 1264, "ext": "js", "max_stars_repo_path": "src/hooks/useComponentVisible.js", "max_stars_repo_name": "germancutraro/react-sagas-boilerplate", "max_stars_repo_stars_event_min_datetime": "2021-05-30T23:49:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T00:03:00.000Z", "max_issues_repo_path": "src/hooks/useComponentVisible.js", "max_issues_repo_name": "germancutraro/react-sagas-boilerplate", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hooks/useComponentVisible.js", "max_forks_repo_name": "germancutraro/react-sagas-boilerplate", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.0888888889, "max_line_length": 72, "alphanum_fraction": 0.6368670886}
import { useState, useEffect, useRef } from 'react';

const useComponentVisible = (
  initialIsVisible, // initial state
  animationTime, // animation on close
  onClose // onclose function
) => {
  const [isComponentVisible, setIsComponentVisible] = useState(
    initialIsVisible
  );
  const ref = useRef(null);

  const handleClickOutside = event => {
    if (ref.current && !ref.current.contains(event.target)) {
      if (isComponentVisible) {
        if (animationTime) {
          setIsComponentVisible(0.5);
          setTimeout(() => {
            onClose && onClose();
            setIsComponentVisible(false);
          }, animationTime);
        } else {
          setIsComponentVisible(false);
          onClose && onClose();
        }
      }
    }
  };

  const handleEscape = e => e.key === 'Escape' && handleClickOutside(e);

  useEffect(() => {
    document.addEventListener('click', handleClickOutside, true);
    document.addEventListener('keydown', handleEscape, true);
    return () => {
      document.removeEventListener('click', handleClickOutside, true);
      document.removeEventListener('keydown', handleEscape, true);
    };
  });

  return { ref, isComponentVisible, setIsComponentVisible };
};

export default useComponentVisible;
