LazyRenderer.tsx 719 B

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