useRef、useMemo、useCallback 挂钩的生产用例是什么?

What are production use cases for the useRef, useMemo, useCallback hooks?

在许多 YouTube 教程视频中看到的 counter 示例之外,[=10] 的 practical/real-world 用例是什么=] 和 useCallback?

此外,我只看到 输入焦点 useRef 挂钩的示例。

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

useRef:

语法: const refObject = useRef(initialValue);

它只是 return 一个普通的 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. 存储可变值,如 instance variable (in class)
  3. 渲染图counter
  4. 要在 setTimeout / setInterval 中使用的值,不会出现 问题。

useMemo:

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

它 return 是一个 memoized 。这个钩子的主要目的是“性能优化”。在需要时谨慎使用它以优化性能。

它接受两个参数——“create”函数(应该 return 要记忆的值)和“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])

它return是一个memoized函数(或回调)。

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

一些常见的用法,例子:

  1. 将 memoized 函数传递给子组件(通过 React.memoshouldComponentUpdate 使用 shallow equal - Object.is 进行了优化)以避免由于作为 props 传递的函数而不必要地重新渲染子组件.

例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. 将记忆函数作为依赖项传递给其他挂钩。

示例 2,没有 useCallback,不好(但是 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 <>...<>
}

这些钩子规则或实现将来可能会发生变化。因此,请确保检查文档中的 hooks reference。此外,重要的是要注意 eslint-plugin-react-hook 关于依赖项的警告。如果省略这些钩子的任何依赖性,它将指导您。

我想补充一下,对于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

更干净

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