react-use icon indicating copy to clipboard operation
react-use copied to clipboard

useEffectOnce update/fix

Open federico-pi opened this issue 3 years ago • 1 comments

Making sure useEffectOnce actually runs only once. Particularly preventing React 18 from rendering twice in development mode.

federico-pi avatar Jun 08 '22 14:06 federico-pi

Take a look at https://dev.to/iamyoki/comment/1pfc9

function useEffectOnce(effect) {
  const effectFn = useRef(effect)
  const destroyFn = useRef()
  const effectCalled = useRef(false)
  const rendered = useRef(false)
  const [, refresh] = useState(0)

  if (effectCalled.current) {
    rendered.current = true
  }

  useEffect(() => {
    if (!effectCalled.current) {
      destroyFn.current = effectFn.current()
      effectCalled.current = true
    }

    refresh(1)

    return () => {
      if (rendered.current === false) return
      if (destroyFn.current) destroyFn.current()
    }
  }, [])
}

This seems to be designed to skip a render, but it's not clear why.

mrclay avatar Jul 26 '22 19:07 mrclay