What is the actual cost of defining a new function inside the rendering method?

I am trying to clarify the pros and cons of having a new function declaration in a reaction rendering method.

Consider a rendering method, for example:

  render () {
    return (<SomeComponent somePropWithoutEventBind={() => console.log('not so dangerous?')} />)
  }

In the above example, it somePropWithoutEventBinddoes not bind to the DOM event: the reaction will check for prop changes, and every time the render is called this, this parameter has changed - since this is a new function, therefore it never coincides with the previous one, it is expensive, but nothing grandiose.

Now in this case

  render () {
    return (<input onChange={() => console.log('dangerous?')} />)
  }

onChange prop is binding to the DOM (something like addEventListener) so that every rendering should again removeEventListenerand addEventListener? Is this the main reason for refusing to declare functions inside the rendering method?

, , , .

+4
1

- .

DOM ( DOM) : <button onClick={_ => this.setState({ hide: true })}>Hide Me</button>} , DOM . ( : DOM-, add/removeEventListener, SyntheticEvent, DOM, DOM)

( Container, / . , -

render() {
  // you won't run into unnessary re-render issue 
  // when you use `onClick={this.handleClick}` since the function reference doesn't change
  // while most perf tricks done by react bindings are relying on shallow compare of props/state
  return (
    <ComplexContainer onClick={_ => this.setState({ forceReRender: true})}>
      <Child1 />
      <Child2>
        <NestedChild1 />
        <NestedChild2 />
      </Child2>
    </ComplexContainer>
  )
}

, , , ComplexContainer, , , DevTools .

, , : , , , , . : ,

< > , DOM, . API event.preventDefault()/event.preventPropagation() .., , , . , . >

+3

Source: https://habr.com/ru/post/1692997/


All Articles