State between renders

Conclusion: As long as the same component is maintained in the DOM, the state for it is maintained as well.

by mihaibirsan

HTML

<div id="app"></div>

<!--
Conclusion: As long as the same component is maintained in the DOM, the state for it is maintained as well.
-->

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

p {
  margin: 8px 0;
}

button {
  font-weight: bold;
}

React

class Hello extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0
    }
  }
  
  pushState = () => {
  	this.setState({ count: this.state.count + 1 })
  }
  
  render() {
    return <div>
      <p>Hello {this.props.name}</p>
      <p>Does it keep state? {this.state.count || "Not yet."}</p>
      <button onClick={this.pushState}>Push</button>
    </div>;
  }
}

class SomethingLikeTabs extends React.Component {
  state = {
  	tab1: true,
    tab2: false,
    now: Date.now(),
  }
  
	render() {
    const tabs = [
    	<Hello name={`Tab1: ${this.state.now}`} />,
      <Hello name={`Tab2: ${this.state.now}`} />,
    ];
  	return <div>
  	  <button onClick={() => this.setState({ tab1: true, tab2: false, })}>Tab 1</button>
  	  <button onClick={() => this.setState({ tab1: false, tab2: true, })}>Tab 2</button>
      <button onClick={() => this.setState({ tab1: true, tab2: true, })}>All</button>
      —
      <button onClick={() => this.setState({ now: Date.now() })}>Refresh name</button>
      {this.state.tab1 && tabs[0]}
      {this.state.tab2 && tabs[1]}
  	</div>
  }
}

ReactDOM.render(
  <SomethingLikeTabs />,
  document.getElementById('app')
)