useMemo 返回的一个经过缓存的值,useMemo的值参与渲染
如果 useMemo返回一个函数,就等价于 useCallback

  • useCallback只创建一次事件句柄
  • useCallback是 useMemo的一种变体
  1. function App(props) {
  2. const [count, setCount] = useState(0)
  3. // useMemo的值参与渲染
  4. const plus = useMemo(() => {
  5. return count * 2
  6. }, [ count === 3])
  7. // 等价于 useCallback(fn)
  8. const onClick = useMemo(() =>{
  9. return () => { console.log('')}
  10. })
  11. const onClick2 = useCallback(() => {
  12. console.log('callback click')
  13. }, [count])
  14. }

useMemo循环依赖bug

useMemo循环依赖,会死循环,错误的用法❌

  1. function App(props) {
  2. const [count, setCount] = useState(0)
  3. // useMemo的值参与渲染
  4. const multi = useMemo(() => {
  5. return count * 2
  6. }, [ count === 3])
  7. const plus = useMemo(() =>{
  8. return multi + 10
  9. }, [multi]) // ❌
  10. }