Created
August 22, 2017 12:37
-
-
Save pokorson/cb8242a8bf6fa003c98c36b8515e3c89 to your computer and use it in GitHub Desktop.
Stateless vs Statefull components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
const StatelessFunctionalComponent = ({ title }) => { | |
console.log("StatelessFunctionalComponent"); | |
return ( | |
<div> | |
hello from stateless functional component {title} | |
</div> | |
); | |
}; | |
class StatefullClassComponent extends React.PureComponent { | |
// React.PureComponent implements such function | |
shouldComponentUpdate(nextProps, nextState) { | |
if (this.props.stateForClass === nextProps.stateForClass) return false; | |
return true; | |
} | |
render() { | |
console.log("StatefullClassComponent"); | |
return ( | |
<div> | |
props: {this.props.stateForClass} | |
</div> | |
); | |
} | |
} | |
class Home extends React.Component { | |
state = { | |
timestamp: new Date().getTime(), | |
stateForClass: new Date().getTime(), | |
}; | |
render() { | |
console.log("Home"); | |
return ( | |
<div> | |
<button onClick={() => this.setState({ timestamp: new Date().getTime() })}> reload parent! </button> | |
<button onClick={() => this.setState({ stateForClass: new Date().getTime() })}> | |
{" "}reload class component!{" "} | |
</button> | |
<p> | |
timestamp: {this.state.timestamp} | |
</p> | |
<StatefullClassComponent stateForClass={this.state.stateForClass} /> | |
<StatelessFunctionalComponent title="test title for stateless" /> | |
</div> | |
); | |
} | |
} | |
export default Home; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment