Inline functions in React cause re-renders?

I read in an article that if you have some code like:

class Parent extends Component {
  render() {
    return (
      <Child
        onClick={() => console.log('You clicked!')}
     />
    );
  }
}

Child will be re-rendered every time Parent re-renders, even if there’s no change in its props, only because the onClick function is inline and so it creates a new reference on every render.

However, even after moving that function outside of render(), Child re-rendered.. so what am i missing here?

In addition, that article also mentioned that inline functions increases a React app’s memory footprint, since a new function reference is created on each render. Is that true? Doesn’t JS have some sort of automatic garbage collection?

Answer

A couple of things, what you have posted only works for Class components, and as to why it works with Class components is that you are creating a callback function and binding it to the instance of the component, therefore each render of the component, it is the same callback function instance being used.

More reading on this https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/ under “Why don’t we need to bind ‘this’ for Arrow functions?”

For a function component, it’s different, there is no class instance, you can use the useCallback hook that will memoize a callback, given a set of dependencies remain the same.

As someone pointed out in the comments you should only really aim to memoize callbacks etc though when they will prevent rerenders of large/deep children