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

The Hook

1import { useRef } from 'react'
2
3function useIsFirstRender(): boolean {
4 const isFirst = useRef(true)
5
6 if (isFirst.current) {
7 isFirst.current = false
8
9 return true
10 }
11
12 return isFirst.current
13}
14
15export default useIsFirstRender

Usage

1import React, { useEffect, useState } from 'react'
2
3import { useIsFirstRender } from 'usehooks-ts'
4
5export default function Component() {
6 const isFirst = useIsFirstRender()
7 const [data, setData] = useState<number>(0)
8
9 useEffect(() => {
10 console.log('Normal useEffect', { data })
11 }, [data])
12
13 return (
14 <div>
15 <p>Open your console</p>
16 <p>Is first render: {isFirst ? 'yes' : 'no'}</p>
17 <button onClick={() => setData(Date.now())}>Update data</button>
18 </div>
19 )
20}

Edit on CodeSandbox

See a way to make this page better?
Edit there »