Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Returning null from setState

Pax Jeci
seal-mask
.a{fill-rule:evenodd;}techdegree
Pax Jeci
Full Stack JavaScript Techdegree Student 730 Points

Why Header Component get Re-rendr in Below Example

App.js
import React from 'react';
import Header from './Header';

class  App extends React.Component {

  state = {
    selectedName : ''
  }

  updatePlayer = name => {
    const _name = name;
    this.setState( prevState => {
      if(_name === prevState.selectedName){
        console.log('SAME');
        return null;
      }
      else {
        console.log('NOT SAME');
        return {
          selectedName : name
        }
      } 

    })
  }


  render () {
    return (    
      <div className="container">
        <button onClick={()=>this.updatePlayer('Player 1')}>Player 1</button>
        <button onClick={()=>this.updatePlayer('Player 2')}>Player 2</button>
        <button onClick={()=>this.updatePlayer('Player 3')}>Player 3</button>

        <Header name={this.state.selectedName} />

      </div>
    )
  }

}

export default App;
Header.js
import React from 'react';

class Header extends React.Component{
  renderCount = 0;
  render () { 
    console.log("renderCount  => ",(++this.renderCount));
    return (
      <header>
         <p>{this.props.name}</p>
      </header>
    )
    }
}

export default Header;