IONIC V4 & REACT JS | HOOKS | BASICS

Share the post

 Ionic V4 React – Hooks

Hello All,

In last topic we discuss about React installation using Ionic 4.Also, we discuss the Project structure of the Ionic 4 React application & in example we used the useState Hook in example. Now, Today we will discuss about Hooks in React JS. 

What is Hooks ?


Basically, Hooks are newly added API reference in React 16.8

Hooks are useful to use state without using or writing a class.

The Basic Hooks are as follows :

  • useState
  • useEffect
  • useContext

useState :

It returns a state value and setState function to update with the new value. In short we are able to update any value using this state.

Please see below example for more details :

       

import {

  IonInput, IonItem, IonLabel, IonContent, IonHeader, IonTitle, IonToolbar,

  IonButtons, IonButton

} from '@ionic/react';

import React, { useState } from 'react';


const Home: React.FunctionComponent = () => {


  const [count, setState] = useState(0);


  return (

    <>

      <IonHeader>

        <IonToolbar>

          <IonTitle>Ionic useState Example</IonTitle>

        </IonToolbar>

      </IonHeader>

      <IonContent className="ion-padding">


        <IonLabel>Updated count</IonLabel>

        <IonTitle>{count}</IonTitle>


        <IonToolbar>

          <IonButtons slot="start">

            <IonButton color="secondary" onClick={() => {

              console.log(count);

              setState(count => count + 1)

            }}>Change default value</IonButton>

          </IonButtons>

        </IonToolbar>

      </IonContent>

    </>

  );

};


export default Home;

In above example,

       
const [count, setState] = useState(0);


here we are initializing the count with value 0 & calling a function called setState on click of a button Change default value. In setState function we are increasing a count value by 1. So, If you run the above application you can able to see the updated value of count.

Please see below image for output : 

Output

We will see the other hooks in the later sessions…

Leave a Comment