美文网首页
useMemo和useCallback

useMemo和useCallback

作者: 郁南 | 来源:发表于2019-10-07 16:30 被阅读0次

    参考文章:链接

    useMemo

    import React, { useState, useMemo, useCallback, useEffect } from 'react';
    
    export default function WithMemo() {
      const [count, setCount] = useState(1);
      const [val, setValue] = useState('');
      
      /** 只有count变化,expensive函数才会执行 */
      const expensive = useMemo(() => {
        console.log('compute');
        let sum = 0;
        for (let i = 0; i < count * 100; i++) {
          sum += i;
        }
        return sum;
      }, [count]);
    
      return (
        <div>
          <h4>
            {count}-{expensive}
          </h4>
          {val}
          <div>
            <button onClick={() => setCount(count + 1)}>+c1</button>
            <input value={val} onChange={event => setValue(event.target.value)} />
          </div>
        </div>
      );
    }
    

    useCallback

    import React, { useState, useMemo, useCallback, useEffect } from 'react';
    
    function Child(props: any) {
      console.log('Parent数据有变化都会进来');
      const [count, setCount] = useState(() => props.callback());
      useEffect(() => {
        console.log('callback变化的时候才会再次执行setCount');
        setCount(props.callback());
      }, [props.callback]);
      return <div>{count}</div>;
    }
    
    export default function Parent() {
      const [count, setCount] = useState(1);
      const [val, setVal] = useState('');
    
      /** 类似于useMemo函数 */
      const callback = useCallback(() => {
        return count;
      }, [count]);
    
      return (
        <div>
          <h4>{count}</h4>
          <h4>{val}</h4>
          <Child callback={callback} />
          <div>
            <button onClick={() => setCount(count + 1)}>+</button>
            <input value={val} onChange={event => setVal(event.target.value)} />
          </div>
        </div>
      );
    }
    

    相关文章

      网友评论

          本文标题:useMemo和useCallback

          本文链接:https://www.haomeiwen.com/subject/dlumpctx.html