5

除了在许多 YouTube 教程视频中看到的例之外,和的实际/现实用例是什么?useMemouseCallback

另外,我只看到了钩子的输入焦点示例。useRef

请分享您为这些钩子找到的其他用例。

4

3 回答 3

32

useRef

句法: const refObject = useRef(initialValue);

它只是返回一个普通的 JavaScript对象。它的值可以根据需要多次访问和修改(可变性),而不必担心“重新渲染”。

它的值将在组件生命周期内持续存在(不会重置为initialValue函数组件中定义的与普通* 对象不同的对象;它会持续存在,因为它useRef为您提供了相同的对象,而不是在后续渲染中创建新对象)。

如果您在控制台上编写const refObject = useRef(0)和打印refObject,您会看到日志是一个对象 - { current: 0 }

*普通对象 vs refObject,例如:

function App() {
  const ordinaryObject = { current: 0 } // It will reset to {current:0} at each render
  const refObject = useRef(0) // It will persist (won't reset to the initial value) for the component lifetime
  return <>...</>
}

几个常见的用途,例子:

  1. 要访问DOM<div ref={myRef} />
  2. 存储可变值,如实例变量(在类中)
  3. 渲染计数器
  4. setTimeout/setInterval没有过时关闭问题的情况下使用的值。

useMemo

语法const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

它返回一个记忆 。这个钩子的主要目的是“性能优化”。在需要时谨慎使用它来优化性能。

它接受两个参数——“create”函数(它应该返回一个要记忆的值)和“dependency”数组。只有当依赖项之一发生更改时,它才会重新计算记忆值。

几个常见的用途,例子:

  1. 在渲染时优化昂贵的计算(例如对数据的操作,如排序、过滤、更改格式等)

未记忆的例子:

function App() {
  const [data, setData] = useState([.....])

  function format() {
    console.log('formatting ...') // this will print at every render
    const formattedData = []
    data.forEach(item => {
      const newItem = // ... do somthing here, formatting, sorting, filtering (by date, by text,..) etc
      if (newItem) {
        formattedData.push(newItem)
      }
    })
    return formattedData
  }

  const formattedData = format()

  return <>
    {formattedData.map(item => <div key={item.id}>
      {item.title}
    </div>)}
  </>
}

记忆的例子:

function App() {
  const [data, setData] = useState([.....])

  function format() {
    console.log('formatting ...') // this will print only when data has changed
    const formattedData = []
    data.forEach(item => {
      const newItem = // ... do somthing here, formatting, sorting, filtering (by date, by text,..) etc
      if (newItem) {
        formattedData.push(newItem)
      }
    })
    return formattedData
  }

  const formattedData = useMemo(format, [data])

  return <>
    {formattedData.map(item => <div key={item.id}>
      {item.title}
    </div>)}
  <>
}

useCallback

语法const memoizedCallback = useCallback(() => { //.. do something with a & b }, [a, b])

它返回一个记忆 函数(或回调)。

它接受两个参数——“函数”和“依赖”数组。仅当依赖项之一发生更改时,它将返回新的即重新创建的函数,否则它将返回旧的即记忆的函数。

几个常见的用途,例子:

  1. 将记忆函数传递给子组件(使用React.memoshouldComponentUpdate使用浅等优化Object.is)以避免由于作为道具传递的函数而不必要地重新渲染子组件。

示例 1,没有useCallback

const Child = React.memo(function Child({foo}) {
  console.log('child rendering ...') // Child will rerender (because foo will be new) whenever MyApp rerenders
  return <>Child<>
})

function MyApp() {
  function foo() {
    // do something
  }
  return <Child foo={foo}/>
}

示例 1,其中useCallback

const Child = React.memo(function Child({foo}) {
  console.log('child rendering ...') // Child will NOT rerender whenever MyApp rerenders
  // But will rerender only when memoizedFoo is new (and that will happen only when useCallback's dependency would change)
  return <>Child<>
})

function MyApp() {
  function foo() {
    // do something
  }
  const memoizedFoo = useCallback(foo, [])
  return <Child foo={memoizedFoo}/>
}
  1. 将 memoized 函数作为依赖项传递给其他钩子。

示例 2,没有useCallback, Bad (但eslint-plugin-react-hook会警告您纠正它):

function MyApp() {
  function foo() {
    // do something with state or props data
  }
  useEffect(() => {
    // do something with foo
    // maybe fetch from API and then pass data to foo
    foo()
  }, [foo])
  return <>...<>
}

示例 2,使用useCallback, 好:

function MyApp() {
  const memoizedFoo = useCallback(function foo() {
    // do something with state or props data
  }, [ /* related state / props */])

  useEffect(() => {
    // do something with memoizedFoo
    // maybe fetch from API and then pass data to memoizedFoo
    memoizedFoo()
  }, [memoizedFoo])
  return <>...<>
}

这些钩子规则或实现将来可能会改变。因此,请务必检查文档中的钩子参考。此外,重要的是要注意有关依赖关系的 eslint-plugin-react-hook警告。如果省略这些钩子的任何依赖,它将指导您。

于 2021-03-14T15:51:00.827 回答
1

我想补充一点,对于 useMemo,我通常在我想同时结合 useState 和 useEffect 时使用它。例如:

...
const [data, setData] = useState(...);
const [name, setName] = useState("Mario");
// like the example by ajeet, for complex calculations
const formattedData = useMemo(() => data.map(...), [data])
// or for simple state that you're sure you would never modify it directly
const prefixedName = useMemo(() => NAME_PREFIX + name, [name]);

我不知道是否会有性能问题,因为文档声明 useMemo 应该用于昂贵的计算。但我相信这比使用 useState 更干净

于 2021-06-16T03:12:40.220 回答
0

useMemo始终用于性能优化。小心添加所有需要的 deps。

于 2022-01-22T13:26:17.000 回答