什么时候使用无依赖vs.直接分配的useEffect? [英] When to use useEffect without dependencies vs. direct assignment?

查看:45
本文介绍了什么时候使用无依赖vs.直接分配的useEffect?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个React挂钩,允许我在组件中使用 setInterval .为此,我需要将最新版本的回调保留在ref中,以便以后可以从时间间隔的范围进行访问.

I am writing a React hook that allows me to use setInterval in my components. In order to do so I need to keep the latest version of the callback in a ref so that it can be accessed from the scope of the interval later on.

到目前为止,这是我的代码:

This is my code so far:

import { useRef, useEffect } from 'react'

export default function useInterval(
  callback: () => void,
  delay: number | null,
) {
  const callbackRef = useRef(callback)

  // Remember the latest callback.
  useEffect(() => {
    callbackRef.current = callback
  })

  useEffect(() => {
    // Don't schedule if no delay is specified.
    if (delay === null) {
      return
    }

    const id = setInterval(() => callbackRef.current(), delay)

    return () => clearInterval(id)
  }, [delay])
}

我的问题是有关 useEffect 的第一个实例,其中将最新值传递给引用.根据React文档,此代码将在我的组件渲染后执行.

My question is about the first instance of useEffect where the latest value is passed to the ref. According the the React documentation this code will execute after my component has rendered.

我可以想象当将ref传递给元素时,这很有用,因此可以确保在呈现之后它具有一个值.但是,如果我的代码不关心组件何时呈现,将其保留在 useEffect 中是否仍然有意义?

I can imagine this is useful when you are passing a ref to an element so you can be sure that it has a value after it has rendered. But if my code doesn't care about when the component renders, does it still make sense to keep this in a useEffect?

按如下方式重写代码是否有意义:

Would it make sense that I rewrite the code as follows:

import { useRef, useEffect } from 'react'

export default function useInterval(
  callback: () => void,
  delay: number | null,
) {
  const callbackRef = useRef(callback)

  // Remember the latest callback.
  callbackRef.current = callback

  useEffect(() => {
    // Don't schedule if no delay is specified.
    if (delay === null) {
      return
    }

    const id = setInterval(() => callbackRef.current(), delay)

    return () => clearInterval(id)
  }, [delay])
}

推荐答案

何时在没有依赖与直接分配的情况下使用 useEffect ?

来自文档:

When to use useEffect without dependencies vs. direct assignment?

From docs:

效果挂钩可让您在功能组件中执行副作用

The Effect Hook lets you perform side effects in function components

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆