Skip to content

Do Not Run First Mount

Prevent Side Effect to run when component did first mount, but when the next state changes, do something

Rizki Maulana Citra

Created by / Rizki Maulana Citra

useLayoutEffect is similiar to useEffect, see the difference here

JS
export default function LovelyComponent() {
  const mounted = useRef(false)

  const doSomething = useCallback(() => {
    // do something
  }, [])

  useLayoutEffect(() => {
    if (!mounted.current) {
      mounted.current = true
      return
    }

    doSomething()
  }, [doSomething])

  return (
    <>
      <p>Little ice cream nuggets!</p>
    </>
  )
}
Edit on GitHub