import { useEffect, useState } from "react"; import { useDispatch } from "react-redux"; import { addLayer, removeLayer, showLayer, hideLayer } from "~store/ui/reducer"; import { UILayer } from "~store/ui/state"; export default function useUILayer(data: UILayer, show: boolean) { const dispatch = useDispatch(); const [id] = useState(data.type + "-" + Math.random().toString(32).slice(2)); const [visible, setVisible] = useState(show); useEffect(() => { dispatch(addLayer({ id, data })); return () => { dispatch(removeLayer({ id })); }; }, []); useEffect(() => { if (visible) { dispatch(showLayer({ id })); } else { dispatch(hideLayer({ id })); } }, [visible]); if (show != visible) { setVisible(show); } return id; }