Skip to content

Instantly share code, notes, and snippets.

@sasial-dev
Last active August 17, 2024 06:06
Show Gist options
  • Save sasial-dev/fbdbb06c2a32aa2f08e827bb84bb8efa to your computer and use it in GitHub Desktop.
Save sasial-dev/fbdbb06c2a32aa2f08e827bb84bb8efa to your computer and use it in GitHub Desktop.
import React, { useEffect, useState } from "@rbxts/react";
import { useSelector } from "@rbxts/react-reflex";
interface RouteProps extends React.PropsWithChildren {
path?: string;
visible?: boolean;
mount?: () => Promise<void>;
unmount?: () => Promise<void>;
}
export = React.memo<RouteProps>((props) => {
const currentRoute = useSelector((state) => state.gui.menu.route);
const isOpen = (props.path && props.path === currentRoute) || props.visible || false;
const [shouldRender, setShouldRender] = useState(isOpen);
useEffect(() => {
// on mount only
if (isOpen === true && props.mount) {
props.mount();
}
}, []);
// we can't use await as we cannot yield in a useEffect
const updateShouldRender = () => {
if (shouldRender !== isOpen) {
if (isOpen === true) {
if (props.mount) {
props.mount().then(() => setShouldRender(isOpen));
} else {
setShouldRender(isOpen);
}
} else if (props.unmount) {
props.unmount().then(() => setShouldRender(isOpen));
} else {
setShouldRender(isOpen);
}
}
};
useEffect(updateShouldRender, [isOpen]);
return shouldRender && props.children;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment