1

I understand that if we bind a function inside a constructor it will load only once and creates a function in webpack bundle.js file. But if we do anywhere else like inside render It creates a new function every time your component re renders.

But the big question here is how much space it occupies whenever a function is created and can’t webpack reject the new function to be created when it is already created once?

Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
  • 1
    Its not upto webpack to optmize on it since it happens during run time and not compile time. If you want to void binding inside render check this https://stackoverflow.com/questions/45053622/how-to-avoid-binding-inside-render-method/45053753#45053753 – Shubham Khatri Jan 10 '18 at 07:12
  • Yeah I understand that the best place for binding is constructor. But what I was thinking like why webpack allows duplicate functions to be created when we do binding directly in render. Got it now we have to do something with babel plugins to avoid duplicate functions – Hemadri Dasari Jan 17 '18 at 07:54

1 Answers1

1

Webpack is not responsible for binding functions in the constructor. Webpack is a module bundler which build and bundle your app. With regard to javascript, it handles transpiling code with plugins like babel. Space for these bound function is a runtime property and cannot be handled by webpack optimizations.

Alternative to binding is use babel preset called transform class properties.

class AComponent extends React.Component{

    onClick = ()=>{
        //handle click
    }

    render(){
        return (
            <div onClick={this.onClick}></div>
        )
    }

}

Using this removes unnecessary allocations for new functions for each render call. But you have to use babel plugin class properties transform.

XPD
  • 1,121
  • 1
  • 13
  • 26