useUpdateEffect()

Just modified version of useEffect that is skipping the first render.

See also:

The Hook

1import { DependencyList, EffectCallback, useEffect } from 'react'
2
3import { useIsFirstRender } from 'usehooks-ts'
4
5function useUpdateEffect(effect: EffectCallback, deps?: DependencyList) {
6 const isFirst = useIsFirstRender()
7
8 useEffect(() => {
9 if (!isFirst) {
10 return effect()
11 }
12 // eslint-disable-next-line react-hooks/exhaustive-deps
13 }, deps)
14}
15
16export default useUpdateEffect

Usage

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

Edit on CodeSandbox

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