Reference useLayoutEffect

  • useLayoutEffect is an alternative to useEffect
  • 'useLayoutEffect' runs synchronously, where as 'useEffect' runs asynchronously
  • 'useLayoutEffect' is used when the structure of the DOM is effected by the state change, as it will draw the DOM first and then insert the values/data.
  • helps prevent strange resizing behoviour in the DOM as it loads.
WDS Video on this Hook
import React, { useLayoutEffect, useRef, useState } from "react"; function ExampleUseLayoutEffect() { const [show, setShow] = useState(false); const popup = useRef(); const btn = useRef(); // useEffect(() => { useLayoutEffect(() => { if (popup.current == null || btn.current == null) return; const { b } = btn.current.getBoundingClientRect(); popup.current.style.top = `${b + 25}px`; }, [show]); return ( <Stack alignItems={"center"} sx={{ width: "100%", maxWidth: "40dvw", margin: 2, backgroundColor: "lightblue", padding: 7, borderRadius: 15 }}> <Stack direction={"column"} alignItems={"center"} gap={5}> <Button variant="contained" ref={btn} onClick={() => setShow((p) => !p)}> Example </Button> {show && ( <Typography variant="h6" ref={popup} sx={{ marginBottom: 5 }}> Example - I am here </Typography> )} </Stack> </Stack> ) }