What is Hooks ? Explain Hooks in React.

Hooks :- Hooks are the new react feature added in react version 16.8 . Hooks replaced the Class components from react and react Classes are still there.

To keep track on the application state and lifecycle methods we used Hooks in react. To use hooks in application we must import hooks from react as shown in below syntax.

                    
import {useState} from 'react'; 

As you shown we have used useState Hook to keep track the state of application. You will learn it in details in upcoming tutorials.

Below are the basic rules that you need to follow when working with hooks.

Rule 1:- We can only call hooks from react functions.
Rule 2:- Always call hooks at the top level of components.

Hooks will not work inside the Classes. If you need to use states in various components then you can write the custom Hooks so that you can reused it in many components.

Image is not available

In the above Image I have written the Hooks so that you can easily understand about the Hooks. Firstly create a componenent with name HookExample (Keep First Letter in Uppercase of component name) and then import the hooks from react as I have shown in In line number 1 , I have import useState from react into HookExample component.
Inside the function create a Hook using const and [area, setArea] = useState("triangle") and then we have used these into the H1 tag using the onClick events of buttons.
Complete code is attached below so you can copy and paste and then run the application it will works fine.

                    
import { useState } from "react";
function HookExample()
{
const [area, setArea] = useState("triangle");
  return (  <> 
    <h1>You have choosen for  {area}!</h1>
            <button type="button" onClick={() => 
             setArea("triangle")}>
            Triangle</button>
         <button type="button"
                onClick={() => setArea("circle")}
      >Circle</button>
             <button type="button"
                 onClick={() => setArea("rectangle")}
      >Rectangle</button>
                    <button type="button"
                  onClick={() => setArea("square")}
      >Square</button>
    </> 
  );
}
export default HookExample

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.