What does useCallback/useMemo do in React?

前端 未结 2 587
不知归路
不知归路 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 07:10

    This is best used when you want to prevent unnecessary re-renders for better performance.

    Compare these two ways of passing callbacks to child components taken from React Docs:

    1. Arrow Function in Render

    class Foo extends Component {
      handleClick() {
        console.log('Click happened');
      }
      render() {
        return ;
      }
    }
    

    2. Bind in Constructor (ES2015)

    class Foo extends Component {
      constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
      }
      handleClick() {
        console.log('Click happened');
      }
      render() {
        return ;
      }
    }
    

    Assuming ; }

    2. Bind in Constructor (ES2015) -> Memoized callbacks

    function Foo() {
      const memoizedHandleClick = useCallback(
        () => console.log('Click happened'), [],
      ); // Tells React to memoize regardless of arguments.
      return ;
    }
    

    The first way creates callbacks on every call of the functional component but in the second way, React memoizes the callback function for you and the callback is not created multiple times.

    In most cases, it's fine to do the first way. As the React docs state:

    Is it OK to use arrow functions in render methods? Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions.

    If you do have performance issues, by all means, optimize!

提交回复
热议问题