2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(React) ちょっとした改造 useEffect

Last updated at Posted at 2024-11-05

作ったものの使わなかったやつ。

こういうのをやりたくなった時点で、何か useEffect の使い方が間違っているような気がするが...

初回レンダリングだけスキップする useEffect

import type { DependencyList, EffectCallback } from 'react'
import { useEffect, useState } from 'react'

export function useEffectWithoutInitialRender(
  effect: EffectCallback,
  deps?: DependencyList
) {
  const [initialRender, setInitialRender] = useState<boolean>(true)
  useEffect(() => {
    if (initialRender) {
      setInitialRender(false)
      return () => {}
    }
    return effect()
  }, deps)
}

前回の deps を参照できる useEffect

import type { DependencyList } from 'react'
import { useEffect, useState } from 'react'

export function useEffectWithPrevDeps<T>(
  effect: (prevDeps?: T) => void | (() => void),
  deps: T & DependencyList
) {
  const [prevDeps, setPrevDeps] = useState<T>()
  useEffect(() => {
    setPrevDeps(deps)
    return effect(prevDeps)
  }, deps)
}
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?