Binding why? ./resources/react-passing-functions-to-components.resources/unknown_filename.png

options

  • (a) bind in constructor (ES2015)
  • (b) class properties (ES2022)
  • (c) bind in render
  • (d) arrow function in Render
  • ?? why no (e) pass the parent object

(a) bind in constructor (ES2015)

constructor(props) {
super(props)
this.setUser = this.setUser.bind(this)
}

<button onClick={this.handleClick}

(b) class properties (ES2022)

handleClick = () => {
// use 'this'
};

<button onClick={this.handleClick}

(c) bind in render ๐Ÿ˜ž creates a new function each render

<button onClick={this.handleClick.bind(this)}

(d) arrow function in Render ๐Ÿ˜ž creates a new function each render

<button onClick={() => this.handleClick()}

?? why no (e) pass the parent object (if subcomponent)

// parent
class Parent implements IHandleClicksFromChild extends ... {
render() {
<Child clickHandler={this}

//child
interface IHandleClicksFromChild {
click: () => void
}

class Child extends Component<{clickHandler: IHandleClicksFromChild}>

// still uses 'this', so same problem here
this.props.clickHandler.click()

//eg. arrow function in render
<button onClick={() => this.props.clickHandler.click()}
  • maybe causes memory leaks?
  • could pass it as an interface instead of the entire component
  • Child would have to bind then anyway to interact with UI things

Passing parameters

  • arrow function in Render
  • bind in render
  • using data-attributes

prevent function called too often

  • Throttle
  • Debounce
  • requestAnimationFrame throttling

(src: Passing Functions to Components โ€“ React)