Closures are a function definition found inside of a function call, and the definition is re-evaluated every time the function is called. In the React world, render is called every time a component needs to be re-evaluated. A lot of times. If render is called a thousand times, a thousand versions of the arrow function are going to be created. Now, multiply this over all of the components in your React application, and each of the closures that their render methods create!
Of course, each one of these arrow functions will be eligible for garbage collection almost as soon as the next one is created. But we still have to ask are:
- How efficient is it to keep making these functions?
- Can garbage collection keep up with everything that we create?
The solution is to replace the arrow function with a reference to a function that is not re-created for every call to render. Since we do not want functions floating around in global space, preferably a method of the CounterComponent class as on line 32:
That problem may be fixed with the bind method of the the function object: this.increment.bind(this). That creates a new version of the function where this is bound to the CounterComponent instance, which happens to be referenced by this when the bind method is called. When the new function is called, this will always be the CounterComponent instance no matter who invokes it.
When you re-assign the reference in the constructor you are creating a new property in the instance that overrides the prototype method, and the new property is a reference to the bound function-object. That is an additional function-object, but at least only one is created for the instance and used every time the render method is invoked.
http://askjoelit.com/download/ReactCallbacks.zip. The two projects the zip file contains are wrapped with a Node-express application. Remember to use "npm install" and "bower install" to retrieve the dependencies before launching the servers with "npm start."
See the references page.