React custom Hook to reuse modal logic. Accepts a generic element as prop to use in the modal.

Home   »   React custom Hook to reuse modal logic. Accepts a generic element as prop to use in the modal.

import { useState } from 'react';

export function useModal(): [
  boolean,
  (element: T | null) => void,
  () => void,
  T | null,
] {
  const [isOpen, setIsOpen] = useState(false);
  const [element, setElement] = useState(null);

  function onOpen(e: T | null) {
    setIsOpen(true);
    setElement(e);
  }

  function onClose() {
    setIsOpen(false);
    setElement(null);
  }

  return [isOpen, onOpen, onClose, element, setElement];
}

Leave a Reply

Your email address will not be published. Required fields are marked *