How can we change the lifecycle methods to hooks in React with an example

Using of lifecycle methods and their implementation ans will the same example with hooks useState, useEffect.

class App extends Component {
  constructor (props){
    super(props)
    //state
    this.state = {
      users:[],
      laoding:false
    };
  }
  componentWillUnmount(){
    axios('https://therundown-therundown-v1.p.rapidapi.com/affiliates').then(response =>this.setState({
      users: response.data.results,
      loading:false
    }))
  }

  Example for count, as we can count how mnay no. of times we have clicked
  state = {
    count:0
  } 
  increment =() => {
    this.setState({
      count:this.state.count+1
    });
  };
// these are called life cycle methods 
  componentDidMount() {
    document.title = `Clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `Clicked ${this.state.count} times`;
  }
//ends here
  render(){
    return (
      <div>
        <h2>counter app</h2>
        <button onClick={this.increment}>
          Clicked{this.state.count}times
          </button>
      </div>
    );
    // <div class="App">{this.state.users.map(user => <div>{user.cell}</div>)}</div>; // this line is from another example
  }

  Now Using HOOKS for same example
  const App = () => {
    const [count, setCount] = useState(0);
  
    const increment = () => {
      setCount(count + 1);
    };
  // this useEffect will work as the state changes (count chnages so the useEffect will run)
    useEffect(() =>{
      document.title = `Clicked ${count} times`;
    });
    return (
      <div>
        <h2>Counter App</h2>
        <button onClick={increment}>Clicked {count} times</button>
      </div>
    );
  };

Functional Components are fast Faster as they do not have state and lifecycle, react needs to do less work to render these components. These components tend to be shorter and more concise. And these components do not use “this” at all, which makes them easier to understand for beginners.

Leave a comment

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