This is the 31st day of my participation in the August More Text Challenge

What is useMemo?

UseMemo behaves like computed properties in Vue and can detect changes in a value and calculate new values based on the changes. UseMemo caches the results and does not recalculate even if the component is re-rendered if the detection value does not change. This behavior can help avoid expensive calculations on each render. Do not perform operations in useMemo functions that are not related to rendering.

Basic usage of useMemo

function App() {

    const [bool,setBool] = useState(true);
    const [age,setAge] = useState('666');
    
    const result = useMemo(() = > {
        console.log('Age change detected');
        return age * 2; 
    },[age])
    return (
        <div>{age} {bool ? 'true ':' false '}<button onClick={()= >setBool(! Bool)}> point I toggle Boolean</button>
            <button onClick={()= >SetAge (age*1 +1)}> age+1</button>The result is: {result}</div>)}Copy the code

Memo method

The Memo method can be used for performance optimization to prevent component updates if the data in the component has not changed, similar to PureComponent and shouldComponentUpdate in class components.

The basic usage of the Memo method

function App() {
    const [count, setCount] = useState(0);
    return (
        <div>
            <Foo />
            <h1>The current sum is: {count}</h1>
            <button onClick={()= >SetCount (count +1)}> hit me +1</button>
        </div>)}const Foo = memo(function Foo() {
    console.log('Foo is rendered ');
    return (
        <div>This is the Foo component</div>)})Copy the code

What is a useCallback?

Often used for performance optimization, caching functions so that components get the same function instance when re-rendering.

The basic usage of useCallback

The important thing to note here is that the first argument to useCallback is the function we need to cache, and the second argument is an array containing the unchanged target function.

function App() {
    const [count, setCount] = useState(0);
    const resetCount = useCallback(() = > setCount(0),[setCount]);
    return (
        <div>
            <Foo resetCount={resetCount}/>
            <h1>The current sum is: {count}</h1>
            <button onClick={()= >SetCount (count +1)}> hit me +1</button>
            
        </div>)}const Foo = memo(function Foo(props) {
    console.log('Foo is rendered ');
    return (
        <div>This is the Foo component<button onClick={props.resetCount}>I return to zero point</button>
        </div>)})Copy the code

The resources

  • Official document: useCallback
  • Official document: useMemo