Saturday, April 22, 2017

"React components, do you need class to do them properly?" -or- "local state, It's a trap!"

So, I'm looking at and how React has leveraged the class construct and hierarchy in encapsulating the clock class in the example. I'm wondering, is the class construct necessary, and I'm very much hoping it is not. I'm going to try to re-create the example without using the class and extends and sticking with functional javascript. We already know you can use stateless functional components, but can we use local state in a functional component.

It would seem not entirely, you need a stateful component somewhere in your application. It looks like the right place for this is as close to the root of the application as you can get it, if you want to move toward having a single state atom (which looks extremely beneficial). So how can we re-write the react clock example using a stateless functional component.

<div id="container"> 
<!-- This element's contents will be replaced with your component. --> 

function Clock(props) { 
    return <div><h1>Hello, world! </h1> <h2>It is {}. </h2></div> 

var App = React.createClass({ 
    getInitialState: function() { 
        return { date: new Date() }; 
    render: function() { 
        return <Clock date={} />; 
    componentDidMount: function() { 
        this.timerID = setInterval(() => this.setState({date: new Date()}),1000); 

ReactDOM.render( <App /> , 

So, this gets the application state all in one place, in the App class, which we can persist or restore atomically, enabling time travel debugging and keeping us from getting in an inconsistent state. This doesn't necessarily mean you want all state in one place, just that relevant to App.

No comments:

Post a Comment