Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do react render props cause remounting of the child components?

Tags:

reactjs

I was just wondering if people know if using the "render props" pattern causes excessive mounting/unmounting of the child component. For example, adapting from the react docs (https://reactjs.org/docs/render-props.html):

<Mouse>
{mouse => (
    <ShowMousePosition mouse={mouse}/>
  )}
</Mouse>


class ShowMousePosition extends React.Component {
  componentDidMount(){
    console.log('mounting!')
  }
  render () {
    const {mouse} = this.props
    return (
      <p>The mouse position is {mouse.x}, {mouse.y}</p>
    )
  }
}

I know the react docs say:

Using a render prop can negate the advantage that comes from using React.PureComponent if you create the function inside a render method. This is because the shallow prop comparison will always return false for new props, and each render in this case will generate a new value for the render prop.

But, will "mounting!" be called over and over as the user moves the mouse around?

Thanks!

like image 299
tnrich Avatar asked Sep 18 '25 13:09

tnrich


1 Answers

I went ahead and tried to answer my own question using a fiddle. It appears that "mounting!" is not called over and over again:

https://jsfiddle.net/69z2wepo/186690/

Here is the code:

class Hello extends React.Component {
  render() {
    return <Mouse>
   {mouse => (
       <ShowMousePosition mouse={mouse}/>
     )}
   </Mouse>
  }
}

class Mouse extends React.Component {
  constructor(props) {
    super(props);
    this.handleMouseMove = this.handleMouseMove.bind(this);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove(event) {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  }

  render() {
    return (
      <div style={{ height: 800, width: 800 }} onMouseMove={this.handleMouseMove}>

        {/*
          Instead of providing a static representation of what <Mouse> renders,
          use the `render` prop to dynamically determine what to render.
        */}
        {this.props.children(this.state)}
      </div>
    );
  }
}




   class ShowMousePosition extends React.Component {
  componentDidMount(){
    console.log('mountin!')
  }
  render () {
    const {mouse} = this.props
    return (
      <p>The mouse position is {mouse.x}, {mouse.y}</p>
    )
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
like image 112
tnrich Avatar answered Sep 21 '25 04:09

tnrich