useIsFirstRender


Simple React hook that return a boolean;

  • True at the mount time
  • Then always false

See also:

  • useEffectOnce(): A modified useEffect() executed only on mount
  • useUpdateEffect(): A modified useEffect() executed only on updates (skip first render)
  • useIsMounted(): Callback function to avoid Promise execution after component un-mount

Usage

import { useEffect, useState } from 'react'

import { useIsFirstRender } from 'reactchemy'

export default function Component() {
   const isFirst = useIsFirstRender()
   const [data, setData] = useState<number>(0)

   useEffect(() => {
      console.log('Normal useEffect', { data })
   }, [data])

   return (
    <div>
      <p>Open your console</p>
      <p>Is first render: {isFirst ? 'yes' : 'no'}</p>
      <button onClick={() => setData(Date.now())}>Update data</button>
    </div>
   )
}

Hook

import { useRef } from 'react'

export function useIsFirstRender(): boolean {
   const isFirst = useRef(true)

   if (isFirst.current) {
      isFirst.current = false

      return true
   }

   return isFirst.current
}