LazyRenderer.tsx 727 B

1234567891011121314151617181920212223242526272829303132
  1. import React, { useEffect, useState } from 'react';
  2. type Props = {
  3. shouldRender: boolean | (() => boolean),
  4. children: React.ReactElement,
  5. }
  6. export const LazyRenderer = (props: Props): React.ReactElement => {
  7. const { shouldRender: _shouldRender, children } = props;
  8. const [isActivated, setActivated] = useState(false);
  9. const shouldRender = typeof _shouldRender === 'function'
  10. ? _shouldRender()
  11. : _shouldRender;
  12. useEffect(() => {
  13. if (isActivated) {
  14. return;
  15. }
  16. setActivated(shouldRender);
  17. }, [isActivated, shouldRender]);
  18. if (!isActivated) {
  19. return <></>;
  20. }
  21. const child = React.Children.only(children);
  22. return React.cloneElement(child, { visibility: shouldRender });
  23. };