Mohamed El Hossiny

Back-end Developer

Front-end Developer

Freelancer

Senior Software Engineer

Mohamed El Hossiny

Back-end Developer

Front-end Developer

Freelancer

Senior Software Engineer

Blog Post

React Hooks

React Hooks

Day #1
Today I will take you back to find the difference between functional component and stateless component. This will bring us to what react have introduced in the new version it’s all about functional component Before we were not able to add state to functional component and we had to use the Class to be able to implement the state and use the SetState method to update the Current state, Now We Have Hooks, the new feature of react that will help us to use state and update state inside the functional component.

UseState: it’s the new Hook interface that will allow us to use our state inside function. So, what is UseState

Let’s look how it work

Const [count , SetCount] = useState(0) ;

  • That’s is, yes

By using array destruction it accept two array inputs ,

  • the first index is the Current state ,
  • the second index is the function that we will use to update the state
  • So [count] is the current state and [setCount] is the method we are going to use to update the count so we have a naming convention with the use at the beginning. So, lets see it in a real-world code example and show you the difference between the old way and the new way in my code snippets.

The New way of Hooks UseState :

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

The Old way of Using SetState:


class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
Taggs: