What is HOOKs?

  • Hooks are function that let you “Hook into” react state and life cycle features from function components.
  • Hooks don’t work inside classes, they let you use react without classes.

State Hook (useState):

suppose we want to make simple form, to enter the user name and age.

App.js

export default function App(props){        
   const(name, setName) = useState('kiran'); 
   const(age, setAge) = useState('12');        

  function handleNameChange(e){ 
   setName(e.target.value);        
 }         

 function handleAgeChange(e){  
   setAge(e.target.value);        
 }                 

  return( 
    <div className="App">      
       <form style={{ ... }}>             
          <TextField label="Name" style={{ ... }} value= {{ name }} 
             onChange={{ handleNameChange}} />                      
         
          <TextField label="Age" style={{ ... }} value= {{ age }} 
             onChange={{ handleAgeChange}} />                 
      </form>            
    </div> 
  ); 
}

withoutHook.js

export default class App extends component{
    constructor(props){
       super(props);
       this.state={
           name : "kiran",
           age: '12'
        };

        this.handleNameChange = this.handleNameChange.bind(this);
        this.handleAgeChange = this.handleAgeChange.bind(this);
   }

    handleNameChange(e){
       this.setState({ name : e.target.value});
    }

    handleAgeChange(e){
       this.setState({ age: e.target.value});
    }

    render(){
        return(
             <div className="App">
                  <form style={{ ... }}>
                        <TextField label="Name" style={{ ... }} value= {{this.state.name }}  
                             onChange={{ this.handleNameChange}}/>
                         
                       <TextField label="Age" style={{ ... }} value= {{ this.state.age }} onChange={{ this.handleAgeChange}} />
                   </form>
             </div>
       );
    }
} 

Effect Hook(useEffect):
-> sometimes, we want to run some additional code after react has updated the DOM.
-> so we use componentDidMount and componentDidUpdate to do that, as an example if we want to change the website title, we are use react class and put side effect into componentDidMount and compnentDidUpdate.

Without hook:

1. To put the initial data on title;
componentDidMount(){
   document.title = this.state.name + " " + this.state.age;
}

2. now to get the new data, when they are updated we will use componentDidUpdate;
componentDidUpdate(){
   document.title = this.state.name + " " + this.state.age;
}

Using hook:

useEffect similar to componentDidMount and componentDidUpdate;

import React, {useState, useEffect} from 'react';
useEffect(() => {
   document.title = name + ' ' + age;  
});

Leave a Reply

Your email address will not be published. Required fields are marked *