4

Regarding using arrow functions vs class methods bound to this for event handlers, the official documents of React reads:

The problem with this syntax (arrow function) is that a different callback is created each time the LoggingButton (an example component) renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.

Since the new approach recommends using function components instead of classes, how do we resolve the above performance issue?

1
  • How do you use functional components skipping the first page of official React documentation Commented Nov 10, 2019 at 13:29

2 Answers 2

5

Use useCallback to memoize the function. The second parameter to useCallback lets you specify what variables should cause the function to be recreated. If one of them changes, a new callback will be created, but otherwise the same function reference will be reused. If you want to never create a new function, an empty array as the second parameter will do that.

import React, { useCallback } from 'react';

const ExampleComponent = (props) => {
  const onClick = useCallback(() => {
    console.log('got clicked', props.name);
  }, [props.name]);

  return (
    <SomeOtherComponent onClick={onClick} />
  )
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this (binding in the constructor)

constructor(props) {
    super(props);
    
    // option #1: binding in the constructor
    this.handleClick = this.handleClick.bind(this);
  }

or this (class fields syntax)

  // class fields syntax
  handleClick = () => {
    console.log('this is:', this);
  }

Both of these are documented by react just above where the above paragraph is found

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.