Tuesday 17 July 2018

Should you define all properties of a component's state inside the constructor?

So I finished reading this article which basically talks about how v8 and other javascript engines internally cache the "shape" of objects so that when they need to repeatedly access a particular property on an object, they can just use the direct memory address instead of looking up where in that object's memory that particular property is.

That got me thinking, in React you often declare a component's state inside the constructor but don't include all the properties that will eventually be included in the state, for example:

class MyComponent extends React.Component {
   constructor(props) {
       super(props);
       this.state = {
          hasLoaded: false
       };
   }

   componentDidMount() {
       someAjaxRequest.then((response) => {
           this.setState({
              content: response.body,
              hasLoaded: true
           });
       });
   }

   render() {
       return this.state.hasLoaded ?
          <div>{this.state.content}</div> :
          <div>Loading...</div>;
   }
}

Since according to the article, the state object doesn't remain a consistent structure, would doing something like this be less efficient than defining all the possible state's fields in the constructor? Should you always at least add all the properties even giving them a value of null so that the object is always consistent? Will it impact performance in any substantial way?



from Should you define all properties of a component's state inside the constructor?

No comments:

Post a Comment