Understanding constructors with react components

One of the best use of constructor is to define the initial state of the component, which is very useful for any reactjs application.We could bind any event that occurs in our component into the constructors. It can be used to bind event handlers to the component and initializing the local state of the component. The constructor() method is fired before the component is mounted and like most things in React. has a few rules that you should follow when using it. in

  1. Call super(props) before this.props using
  2.    constructor(props){
            super(props);
            console.log(this.props);
       }
    
    In javascript super refers to the parent class constructor. Importantly, you can't use this in a constructor until after you've called the parent contructor. There's a good reason for why Javascript enforce that parent constructor runs before touch this. JavaScript enforces that if you want to use this in a constructor, you have to call super first.
  3. Never setState() inside constructor() call 
  4.     constructor(props){
             super(props);
             console.log(this.props);
       
            this.state ={
               rep :'',
               color: ''
            };
       }
    
    constructor of your component is the perfect place to set the initial state of your component. Instead of using setState() like you would do in other methods in your class, you will need to set the initial state directly. The constructor is the only place that you should assign the local state directly like that.
  5. Avoid this.props to this.state assigning values from 
  6.   constructor(props){
          super(props);
          
          this.state = {
              rep : props.rep,
          }
      }
    
    When you're setting your initial component state in the constructor, you should try to avoid setting values from the properties. If you use the code like above, you would lose the ability to run setState() later on and update the property. Instead of assigning the property directly to the state, you can simply refer the property directy in your code by callong this.props.rep
  7. Bind events all in one place 
  8.   constructor(props){
          super(props);
          this.state = {
               // Sets that initial states
          };
     
          // our event handlers
          this.onClick = this.onClick.bind(this);
          this.onKeyUp = this.onKeyUp.bind(this);
       }
    
    We can easily bind the event handlers into the constructors,as above.
  9. Avoid using side-effects or constructor() subscription in
  10. componentDidMount() which will fire immediatly after the component is mounted and will not give you any trouble if you update the state inside of it.




Comments

Popular posts from this blog

Easy understanding of MVC design architecture

A / B Testing

Firewall