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 https://facebook.github.io/react/docs/state-and-lifecycle.html 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. --> 
</div> 

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

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

 
ReactDOM.render( <App /> , 
    document.getElementById('container') 
); 


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.

https://facebook.github.io/react/docs/state-and-lifecycle.html
https://www.safaribooksonline.com/blog/2015/10/29/react-local-component-state/
https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc

https://github.com/reactjs/redux/issues/1385

No comments:

Post a Comment