react#useLayoutEffect JavaScript Examples

The following examples show how to use react#useLayoutEffect. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: deck-state.jsx    From MDXP with MIT License 6 votes vote down vote up
DeckState = ({children, slide, step, preview = false}) => {
  const params = useParams();
  const rootContext = useRoot();
  const slideNum = (slide !== undefined) ? parseInt(slide) || 0 : parseInt(params.slide) || 0;
  const stepNum = (step !== undefined) ? parseInt(step) || 0 : parseInt(params.step) || 0;
  const slideIndex = getIndex(slideNum, rootContext.slideLength);
  const [state, setState] = useMerger({
    mode: rootContext.mode,
    slideLength: rootContext.slideLength,
    slideIndex,
    stepLength: 1,
    stepIndex: 0,
    rawStepIndex: stepNum,
    preview
  });

  useLayoutEffect(() => {
    if (slideIndex !== state.slideIndex) {
      setState({slideIndex, rawStepIndex: stepNum, stepIndex: 0, stepLength: 1});
    } else if ((stepNum !== state.rawStepIndex)) {
      setState({rawStepIndex: stepNum});
    }
  }, [slideIndex, stepNum]);

  useLayoutEffect(() => {
    if (rootContext.mode !== state.mode) {
      setState({mode: rootContext.mode});
    }
  }, [rootContext.mode]);

  return (
    <DeckContext.Provider value={[state, setState]}>
      {children}
    </DeckContext.Provider>
  );
}
Example #2
Source File: sidebarV1.js    From about-1hive with GNU General Public License v3.0 6 votes vote down vote up
CollapsibleList = ({ node, listData, path, parent, topLevel, atTopLevel }) => {
  const [open, setOpen] = useState(true)

  useLayoutEffect(() => {
    setOpen(node.name.replace(/\d+-/g, '') === path.split('/')[3])
  }, [node.name, path, setOpen])

  const section = node.name.replace(/\d+-/g, '')

  const title = node.name
    .replace(/\d+-/g, '')
    .replace(/-/g, ' ')
    .replace(/(^|\s)\S/g, function(t) {
      return t.toUpperCase()
    })
  return (
    // <StyledSection trigger={title} transitionTime={250} open={open} onClick={() => setOpen(!open)} easing="ease">

    <StyledSection trigger={title} transitionTime={250} open={open} easing="ease">
      {atTopLevel && (
        <StyledLink
          style={{ marginBottom: '.75rem', display: 'inline-block', padding: '0px' }}
          to={`${topLevel}/${section}`}
          isActive={path.split('/')[4] === ''}
        >
          {title}
        </StyledLink>
      )}
      {open && (
        <StyledInset>
          <List data={listData} parent={node.name} slug={parent} path={path} />
        </StyledInset>
      )}
    </StyledSection>
  )
}
Example #3
Source File: ViewPanel.js    From akashlytics-deploy with GNU General Public License v3.0 6 votes vote down vote up
ViewPanel = ({ children, bottomElementId, offset, ...rest }) => {
  const windowSize = useWindowSize();
  const [height, setHeight] = useState(0);
  const ref = useRef();

  useLayoutEffect(() => {
    if (windowSize.height) {
      try {
        const boundingRect = ref.current.getBoundingClientRect();
        const bottomElementRect = document.getElementById(bottomElementId).getBoundingClientRect();
        let height = Math.round(Math.abs(boundingRect.top - bottomElementRect.top));

        if (offset) {
          height -= offset;
        }

        setHeight(height);
      } catch (error) {
        setHeight("auto");
      }
    }
  }, [windowSize, bottomElementId, offset]);

  return (
    <Box ref={ref} style={{ height }} {...rest}>
      {children}
    </Box>
  );
}
Example #4
Source File: Layout.js    From video-streaming-developer-docs with Apache License 2.0 6 votes vote down vote up
Layout = ({ children, homepage, theme, titleType, pageTitle, pageDescription, pageKeywords, tabs, location }) => {
  const is404 = children.key === null;

  useLayoutEffect(() => {
    // eslint-disable-next-line global-require
    const scroll = require('smooth-scroll')('a[href*="#"]', {
      speed: 400,
      durationMin: 250,
      durationMax: 700,
      easing: 'easeInOutCubic',
      clip: true,
      offset: tabs ? 112 : 64,
    });
    return scroll.destroy;
  }, [tabs]);

  return (
    <>
      <Meta titleType={titleType} pageTitle={pageTitle} pageDescription={pageDescription} pageKeywords={pageKeywords} />
      <Header homepage={homepage} is404Page={is404} theme={theme} location={location} />
      <Switcher />
      <Container homepage={homepage} theme={theme}>
        {children}
        <Footer />
      </Container>
    </>
  );
}
Example #5
Source File: useDivHeight.js    From plenty-interface with GNU General Public License v3.0 6 votes vote down vote up
useDivHeight = () => {
  const [divHeight, setDivHeight] = useState('87vh');

  const heightHandler = () => {
    const headerHeight = document.getElementsByClassName('header')[0].clientHeight;
    const viewportHeight = document.documentElement.clientHeight;
    const waDivHeight = viewportHeight - headerHeight - 1;
    // Calculate the height including margins for the swap components
    const swapComponent = document.getElementsByClassName('wrapped-assets-margin-top')[0];
    const swapComponentsMargins =
      parseFloat(window.getComputedStyle(swapComponent)['marginTop']) +
      parseFloat(window.getComputedStyle(swapComponent)['marginBottom']);
    const swapComponentsHeight = swapComponent.clientHeight + swapComponentsMargins + 20;
    // For cases when the swap components overflow the screen, then their height is more than viewport. Hence choose that height as main div height. (Mobile landscape orientation)
    const finalWADivHeight =
      waDivHeight > swapComponentsHeight ? waDivHeight : swapComponentsHeight;
    //Assign the final height to the div. Supporting older browsers as well.
    setDivHeight(`${finalWADivHeight}px`);
  };

  // Debounce to avoid unnecessary multiple resize events triggered by various browsers.
  const updateHeight = useMemo(() => debounce(heightHandler, 50), []);

  // Event listener to listen to window resize event for changing the wrapped assets main div height.
  useLayoutEffect(() => {
    window.addEventListener('resize', updateHeight);
    updateHeight();
    return () => {
      window.removeEventListener('resize', updateHeight);
      updateHeight.cancel();
    };
  }, []);

  return divHeight;
}
Example #6
Source File: RippleEffect.js    From web with GNU General Public License v3.0 6 votes vote down vote up
useRippleClean = (rippleCount, duration, rippleCleanFunction) => {
  useLayoutEffect(() => {
    let bounce = null;
    if (rippleCount > 0) {
      clearTimeout(bounce);

      bounce = setTimeout(() => {
        rippleCleanFunction();
        clearTimeout(bounce);
      }, duration * 2);
    }

    return () => clearTimeout(bounce);
  }, [rippleCount, duration, rippleCleanFunction]);
}
Example #7
Source File: common.js    From actual with MIT License 6 votes vote down vote up
useStableCallback = callback => {
  const callbackRef = useRef();
  const memoCallback = useCallback(
    (...args) => callbackRef.current(...args),
    []
  );
  useLayoutEffect(() => {
    callbackRef.current = callback;
  });
  return memoCallback;
}
Example #8
Source File: useWindowSize.js    From react-builder with GNU General Public License v3.0 6 votes vote down vote up
export function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

  useLayoutEffect(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }

    window.addEventListener("resize", handleResize);

    handleResize();

    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return windowSize;
}
Example #9
Source File: useWindowSize.js    From bonded-stablecoin-ui with MIT License 6 votes vote down vote up
useWindowSize = () => {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener("resize", updateSize);
    updateSize();
    return () => window.removeEventListener("resize", updateSize);
  }, []);
  return size;
}
Example #10
Source File: authContext.jsx    From react-sendbird-messenger with GNU General Public License v3.0 6 votes vote down vote up
function AuthValue() {
    const [isAuth, setIsAuth] = useState(false)
    const [token, setToken] = useState(
        localStorage.getItem('accessToken') || null
    )

    const login = async (user, token) => {
        localStorage.setItem('email', user?.email)
        localStorage.setItem('userId', user?.email)
        localStorage.setItem('displayName', user?.displayName)
        localStorage.setItem('accessToken', token)
        setIsAuth(true)
        setToken(token)
        return true
    }

    const logout = () => {
        localStorage.removeItem('email')
        localStorage.removeItem('userId')
        localStorage.removeItem('displayName')
        localStorage.removeItem('accessToken')
        setIsAuth(false)
    }

    useLayoutEffect(() => {
        setIsAuth(!!localStorage.getItem('accessToken'))
    }, [])

    return {
        isAuth,
        token,
        login,
        logout,
    }
}
Example #11
Source File: DrillEditorAnimationPage.js    From UltimateApp with MIT License 6 votes vote down vote up
PlayEditorPage = ({ navigation, route }) => {
  const [currentAnimation, setCurrentAnimation] = useState(new Drill(route.params.animation));

  const onAnimationChange = (animation) => {
    setCurrentAnimation(animation);
    route.params.onAnimationChange(animation);
  };

  const handleSubmit = () => {
    navigation.navigate('DrillEditorPage');
  };

  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => <HeaderButton icon="check" onPress={handleSubmit} testID="validateButton" />,
    });
  });

  return (
    <View style={styles.drillEditorPage}>
      <View style={styles.centeredView}>
        <AnimationEditor onAnimationChange={onAnimationChange} animation={currentAnimation} uuid="unused_uuid" />
      </View>
      <View style={styles.toolBar}>
        <View style={styles.toolBarItem}>
          <AnimationHistory animation={currentAnimation} onAnimationHistoryChange={onAnimationChange} />
        </View>
      </View>
    </View>
  );
}
Example #12
Source File: themeContext.js    From tailwindcss-multi-theme with MIT License 6 votes vote down vote up
ThemeProvider = ({ children }) => {
  // defaults to light theme
  const [theme, setTheme] = useState('light')

  // set user's preferred color scheme on first load
  useLayoutEffect(() => {
    setTheme(
      !!window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
        ? 'dark'
        : 'light'
    )
  }, [])

  // change theme
  const oldTheme = usePrevious(theme)
  useLayoutEffect(() => {
    document.documentElement.classList.remove(`theme-${oldTheme}`)
    document.documentElement.classList.add(`theme-${theme}`)
  }, [theme, oldTheme])

  function toggleTheme() {
    if (theme === 'light') setTheme('dark')
    else setTheme('light')
  }

  return <ThemeContext.Provider value={{ theme, toggleTheme }}>{children}</ThemeContext.Provider>
}
Example #13
Source File: ThemeContext.js    From windmill-dashboard-react with MIT License 6 votes vote down vote up
ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useStorageTheme('theme')

  // update root element class on theme change
  const oldTheme = usePrevious(theme)
  useLayoutEffect(() => {
    document.documentElement.classList.remove(`theme-${oldTheme}`)
    document.documentElement.classList.add(`theme-${theme}`)
  }, [theme, oldTheme])

  function toggleTheme() {
    if (theme === 'light') setTheme('dark')
    else setTheme('light')
  }

  const value = useMemo(
    () => ({
      theme,
      toggleTheme,
    }),
    [theme]
  )

  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
}
Example #14
Source File: useScrollPosition.jsx    From cosmoscan-front with Apache License 2.0 6 votes vote down vote up
export function useScrollPosition(effect, deps, element, useWindow, wait) {
  const position = useRef(getScrollPosition({ useWindow }));

  let throttleTimeout = null;

  const callBack = () => {
    const currPos = getScrollPosition({ element, useWindow });
    effect({ prevPos: position.current, currPos });
    position.current = currPos;
    throttleTimeout = null;
  };

  useLayoutEffect(() => {
    const handleScroll = () => {
      if (wait) {
        if (throttleTimeout === null) {
          throttleTimeout = setTimeout(callBack, wait);
        }
      } else {
        callBack();
      }
    };

    window.addEventListener('scroll', handleScroll);

    return () => window.removeEventListener('scroll', handleScroll);
  }, deps);
}
Example #15
Source File: SettingsContext.js    From ReactSourceCodeAnalyze with MIT License 6 votes vote down vote up
useLayoutEffect(
    () => {
      switch (displayDensity) {
        case 'comfortable':
          updateDisplayDensity('comfortable', documentElements);
          break;
        case 'compact':
          updateDisplayDensity('compact', documentElements);
          break;
        default:
          throw Error(`Unsupported displayDensity value "${displayDensity}"`);
      }
    },
    [displayDensity, documentElements],
  );
Example #16
Source File: Demos.js    From popper.js.org with MIT License 6 votes vote down vote up
ClippingParent = props => {
  const scrollRef = useRef();

  useLayoutEffect(() => {
    scrollRef.current.scrollTop = 300;
  }, []);

  return <ClippingParentStyled ref={scrollRef} {...props} />;
}
Example #17
Source File: Annotation.js    From label-studio-frontend with Apache License 2.0 6 votes vote down vote up
export function Annotation({ annotation, root }) {
  useLayoutEffect(() => {
    return () => {
      if (annotation && isAlive(annotation)) {
        annotation.resetReady();
      }
    };
  }, [annotation.pk, annotation.id]);
  return root ? Tree.renderItem(root) : null;
}
Example #18
Source File: index.jsx    From erp-crm with MIT License 6 votes vote down vote up
export default function ErpPanel({ config, CreateForm, UpdateForm, DataTableDropMenu }) {
  const dispatch = useDispatch();
  const { state } = useErpContext();
  const { update, read, create, recordPayment, dataTableList, deleteModal } = state;
  useLayoutEffect(() => {
    dispatch(erp.resetState());
  }, []);

  return (
    <>
      <Visibility isVisible={dataTableList.isOpen}>
        <DataTable config={config} DataTableDropMenu={DataTableDropMenu} />
      </Visibility>
      <Visibility isVisible={read.isOpen}>
        <ReadItem config={config} />
      </Visibility>
      <Visibility isVisible={recordPayment.isOpen}>
        <Payment config={config} />
      </Visibility>
      <Visibility isVisible={update.isOpen}>
        <UpdateItem config={config} UpdateForm={UpdateForm} />
      </Visibility>
      <Visibility isVisible={create.isOpen}>
        <CreateItem config={config} CreateForm={CreateForm} />
      </Visibility>

      <Delete config={config} isVisible={deleteModal.isOpen} />
    </>
  );
}
Example #19
Source File: index.jsx    From starter-antd-admin-crud-auth-mern with MIT License 6 votes vote down vote up
function AdminCrudModule({ config, createForm, updateForm }) {
  const dispatch = useDispatch();

  useLayoutEffect(() => {
    dispatch(crud.resetState());
  }, []);

  return (
    <CrudLayout
      config={config}
      fixHeaderPanel={<FixHeaderPanel config={config} />}
      sidePanelBottomContent={
        <CreateForm config={config} formElements={createForm} />
      }
      sidePanelTopContent={
        <SidePanelTopContent config={config} formElements={updateForm} />
      }
    >
      <AdminDataTable config={config} />
      <DeleteModal config={config} />
    </CrudLayout>
  );
}
Example #20
Source File: dropdown.js    From horondi_client_fe with MIT License 6 votes vote down vote up
Dropdown = ({ mappedItems, handler, defaultValue, value, fromSideBar }) => {
  const styles = dropdownStyles({ fromSideBar });
  const [sticky, setSticky] = useState(false);
  const stickyLang = clsx({
    [styles.rootSelect]: true,
    [styles.sticky]: sticky
  });

  useLayoutEffect(() => {
    let componentMounted = true;
    window.addEventListener('scroll', () => {
      if (componentMounted) {
        window.scrollY > 50 ? setSticky(true) : setSticky(false);
      }
    });
    return () => {
      componentMounted = false;
    };
  }, []);

  return (
    <div className={styles.rootItem}>
      <Select
        className={stickyLang}
        defaultValue={defaultValue}
        value={value}
        onChange={handler}
        IconComponent={KeyboardArrowDown}
      >
        {mappedItems}
      </Select>
    </div>
  );
}
Example #21
Source File: useFirstEffect.js    From react-motion-layout with MIT License 6 votes vote down vote up
export default function useFirstEffect(fn, deps) {
  const firstEffect = useRef(true);
  useLayoutEffect(() => {
    if (firstEffect.current) {
      firstEffect.current = false;
      fn();
    }
  }, [fn, ...deps]);
}
Example #22
Source File: App.jsx    From konsta with MIT License 6 votes vote down vote up
function App() {
  const [theme, setTheme] = useState('ios');
  useEffect(() => {
    window.setTheme = (t) => setTheme(t);
    window.setMode = (mode) => {
      if (mode === 'dark') document.documentElement.classList.add('dark');
      else document.documentElement.classList.remove('dark');
    };
  }, []);
  const inIFrame = window.parent !== window;
  useLayoutEffect(() => {
    if (window.location.href.includes('safe-areas')) {
      const html = document.documentElement;
      if (html) {
        html.style.setProperty('--k-safe-area-top', '44px');
        html.style.setProperty('--k-safe-area-bottom', '34px');
      }
    }
  }, []);
  return (
    <KonstaApp theme={theme} safeAreas={!inIFrame}>
      <Router>
        <Routes>
          {routes.map((route) => (
            <Route
              key={route.path}
              path={route.path}
              element={<route.component />}
            />
          ))}
          <Route
            path="/"
            element={<HomePage theme={theme} setTheme={setTheme} />}
          />
        </Routes>
      </Router>
    </KonstaApp>
  );
}
Example #23
Source File: use-window-size.js    From cards with MIT License 6 votes vote down vote up
useWindowSize = () => {
  const [windowSize, setWindowSize] = useState(DEFAULT_SIZE)

  useLayoutEffect(() => {
    setWindowSize(getSize())

    const handleResize = () => setWindowSize(getSize())
    window.addEventListener('resize', handleResize)

    return () => window.removeEventListener('resize', handleResize)
  }, [])

  return windowSize
}
Example #24
Source File: use-layout-effect-component.jsx    From jest-react-hooks-shallow with ISC License 6 votes vote down vote up
UseLayoutComponent = () => {
  const [text, setText] = useState();
  const [buttonClicked, setButtonClicked] = useState(false);

  useLayoutEffect(() => {
    setText(`Button pressed: ${buttonClicked.toString()}`);

    callback();

    return cleanup;
  }, [buttonClicked]);

  return (
    <div>
      <div>{text}</div>
      <button onClick={() => setButtonClicked(true)}>Press me</button>
    </div>
  );
}
Example #25
Source File: useMouseLeave.jsx    From monday-ui-react-core with MIT License 6 votes vote down vote up
export default function useMouseLeave(resetOpenSubMenuIndex, hasOpenSubMenu, ref, setActiveItemIndex) {
  const isMouseEnter = useIsMouseEnter({ ref });
  const prevIsMouseEnter = usePrevious(isMouseEnter);

  useLayoutEffect(() => {
    if (isMouseEnter) return;
    if (isMouseEnter === prevIsMouseEnter) return;
    if (hasOpenSubMenu) return;
    resetOpenSubMenuIndex();
    setActiveItemIndex(-1);
  }, [resetOpenSubMenuIndex, ref, prevIsMouseEnter, isMouseEnter, hasOpenSubMenu, setActiveItemIndex]);

  return isMouseEnter;
}
Example #26
Source File: index.jsx    From covid19-testing with Apache License 2.0 6 votes vote down vote up
Assessment = ({setLanguage}: Props): React.Component => {
  useLayoutEffect(() => {
    // We want to ensure that the user starts at the top of the survey so they can read the full description in case the
    // scroll position is preserved from the previous page.
    window.scrollTo(0, 0);
  }, []);

  return (
    <>
      <Nav setLanguage={setLanguage} />
      <div className={css.headerContainer}>
        <div className={css.headerContent}>
          <Header2 className={css.title}>{config.name}</Header2>
          <Text className={css.description}>{config.description}</Text>
        </div>
      </div>
      <div className={css.surveyContainer}>
        <div className={css.surveyContent}>
          <ConnectedFormPreview viewSchema={config} />
        </div>
      </div>
    </>
  );
}
Example #27
Source File: AreasProvider.js    From generator-webapp-rocket with MIT License 6 votes vote down vote up
useHeader = (initialHeader) => {
    const [get, set] = useContext(HeaderContext);

    useLayoutEffect(() => {
        if (!initialHeader) {
            return;
        }

        set(initialHeader);
        return () => set(null);
    }, []);// eslint-disable-line react-hooks/exhaustive-deps

    return [get, set];
}
Example #28
Source File: hooks.js    From rolwinreevan_gatsby_blog with MIT License 6 votes vote down vote up
useWindowSize = () => {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}
Example #29
Source File: HexInput.jsx    From omatsuri with MIT License 6 votes vote down vote up
export default function HexInput({ className, value, onChange, ...others }) {
  const [theme] = useTheme();
  const ref = useRef(null);
  const [opened, setOpened] = useState(false);
  const closePicker = () => setOpened(false);
  const closeOnEscape = (event) => event.code === 'Escape' && closePicker();

  useClickOutside(ref, closePicker);

  useLayoutEffect(() => {
    window.addEventListener('keydown', closeOnEscape);
    return () => window.removeEventListener('keydown', closeOnEscape);
  }, []);

  return (
    <div className={cx(classes.wrapper, classes[theme], className)} ref={ref}>
      <div className={classes.inputWrapper}>
        <button
          className={classes.control}
          type="button"
          onClick={() => setOpened((o) => !o)}
          style={{ backgroundColor: value }}
        />
        <div className={classes.hash}>#</div>
        <HexColorInput {...others} className={classes.input} color={value} onChange={onChange} />
      </div>
      {opened && <HexColorPicker className={classes.picker} color={value} onChange={onChange} />}
    </div>
  );
}