Wednesday, December 28, 2016

Increasing the Performance of React Callbacks

The React framework is typically a very heavy user of closures or arrow functions in the component classes. Especially since JavaScript 2015 introduced the arrow function, putting the functions inline when the component renders the sub-components binds the functions tightly to the components where they are used.

Since React has moved on to JavaScript 2015 a common example of handling a button click to change state often looks something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React, { Component } from 'react';

"use strict"

export default class CounterComponent extends Component {

    constructor(...args) {

        super(...args);

        this.state = {

            value: 0
        }
    }
    
    render() {

        return (
            <span>
                Value: { this.state.value } &nbsp;
                <input
                    type="button"
                    value="Increment"
                    onClick={ () => { this.setState({ value: this.state.value + 1}) }} />
            </span>
        );
    }
}

The arrow function on line 25 has a big advantage in JavaScript 2015 over the closure definitions from version 5: when it is created "this" is bound to the same object where it was created, the instance of the CounterComponent. But it is still a closure, and the problem is that a new function is created every time the render method is called.