What does useCallback/useMemo do in React?

前端 未结 2 551
不知归路
不知归路 2021-01-30 06:39

As said in docs, useCallback Returns a memoized callback.

Pass an inline callback and an array of inputs. useCallback will return a memoized version of the callback that

2条回答
  •  悲&欢浪女
    2021-01-30 06:53

    I've made a small example to help others understand better how it behaves. You can run the demo here or read the code bellow:

    import React, { useState, useCallback, useMemo } from 'react';
    import { render } from 'react-dom';
    
    const App = () => {
        const [state, changeState] = useState({});
        const memoizedValue = useMemo(() => Math.random(), []);
        const memoizedCallback = useCallback(() => console.log(memoizedValue), []);
        const unMemoizedCallback = () => console.log(memoizedValue);
        const {prevMemoizedCallback, prevUnMemoizedCallback} = state;
        return (
          <>
            

    Memoized value: {memoizedValue}

    New update {Math.random()}

    is prevMemoizedCallback === to memoizedCallback: { String(prevMemoizedCallback === memoizedCallback)}

    is prevUnMemoizedCallback === to unMemoizedCallback: { String(prevUnMemoizedCallback === unMemoizedCallback) }

    ); }; render(, document.getElementById('root'));

提交回复
热议问题