Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. export default const useDelayDialogChildrenRender = ({
  2. children: childrenFromProps,
  3. open,
  4. }: DelayRenderDialogProps) => {
  5. const children = open ? childrenFromProps : <MyLoadingGif />;
  6.  
  7. const closedChildrenRef = useRef<Optional<React.ReactNode>>();
  8. const openedChildrenRef = useRef<Optional<React.ReactNode>>();
  9. const prevOpenRef = useRef<Optional<boolean>>();
  10.  
  11. const { current: closedChildren } = closedChildrenRef;
  12. const { current: openedChildren } = openedChildrenRef;
  13. const { current: prevOpen } = prevOpenRef;
  14.  
  15. // your dialog will need hooks into when the dialog is entered/exited like eg the material-ui dialog
  16. // we don't strictly need modalState here but it may be useful for the component using this hook
  17. const [modalState, setModalState] = useState<'Exited' | 'Entered'>('Exited');
  18.  
  19. const onEntered = useCallback(() => {
  20. setModalState('Entered');
  21. }, [onEnteredFromProps]);
  22.  
  23. const onExited = useCallback(() => {
  24. setModalState('Exited');
  25. }, [onExitedFromProps]);
  26.  
  27. // use layout effect here so we guarantee we capture these ref
  28. // updates synchronously before on entered/exited fire and that we
  29. // don't update ref multiple times in case of a double render
  30. useLayoutEffect(() => {
  31. prevOpenRef.current = open;
  32.  
  33. if (open) {
  34. openedChildrenRef.current = children;
  35. } else {
  36. closedChildrenRef.current = children;
  37. }
  38. }, [open, prevOpen, children]);
  39.  
  40. const childrenToRender =
  41. open && !prevOpen
  42. ? closedChildren || children
  43. : !open && prevOpen
  44. ? openedChildren || children
  45. : children;
  46.  
  47. return {childrenToRender, onEntered, onExited, modalState};
  48. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement