Hook API useMemo and useCallback

useMemo

You pass in the “create” function and an array of dependencies as arguments to useMemo, which recalculates memoized values only when a dependency changes. This optimization helps to avoid costly calculations on every render.

import React, { useState, useMemo } from "react"; export default function UseMemoPage(props) { const [count, setCount] = useState(0); const expensive = useMemo(() => { console.log("compute"); let sum = 0; for (let i = 0; i < count; i++) { sum += i; } return sum; }, [count]); const [value, setValue] = useState(""); return ( <div> <h3>UseMemoPage</h3> <p>expensive:{expensive}</p> <p>{count}</p> <button onClick={() => setCount(count + 1)}>add</button> <input value={value} onChange={event => setValue(event.target.value)} /> </div> ); }Copy the code

useCallback

The inline callback function and an array of dependencies are passed in as arguments to useCallback, which returns an Memoized version of the callback function that is updated only when a dependency changes. It is not very useful when you pass callback data to optimized child components that use references and equality to avoid unnecessary rendering (e.g. ShouldComponentUpdate).

    import React, { useState, useCallback, PureComponent } from "react";
    export default function UseCallbackPage(props) { 
     const [count, setCount] = useState(0);
     const addClick = useCallback(() => { 
       let sum = 0;
       for (let i = 0; i < count; i++) { 
         sum += i;
       }
        return sum;
     }, [count]);
    const [value, setValue] = useState(""); 
        return (
            <div>
             <h3>UseCallbackPage</h3>
             <p>{count}</p>
             <button onClick={() => setCount(count + 1)}>add</button>
             <input value={value} onChange={event => setValue(event.target.value)} />
             <Child addClick={addClick} />
            </div>
        );
    }
    class Child extends PureComponent { 
        render() {
         console.log("child render"); 
         const { addClick } = this.props; 
         return (
          <div>
          <h3>Child</h3>
          <button onClick={() => console.log(addClick())}>add</button>
         </div>
        );
    }
Copy the code

UseCallback (fn,deps) is equivalent to useMome(()=>fn,deps) note that the dependency array is not passed as an argument to the create function. Conceptually, though, it looks like this: all values referenced in the “create” function should appear in the dependency array. In the future, compilers will get smarter and it will be possible to create arrays automatically.