Pages

How to use hooks in react js?

To use hooks in react js, we can use class component features in functional components state, useEffect, etc.


There are many types of Hooks in react.


  1. usestate react

Example of react hooks with useState.


Here, we have taken the state.

const[state,setState] = useState("Anand");


We use setState to update the state. We have taken the default data “Anand”.


Now, we change the state on clicking the button.

<button onClick={() =>setState("Balaji")}>Change Name</button>


On clicking the button, we are providing the default data to the setState. The setState will transfer the data to the state.

Now, the value will be shown as “Balaji”.


Here, we have the full code -


import logo from './logo.svg';

import './App.css';

import React,{useState} from 'react';


function App() {

 const[state,setState] = useState("Anand");


 return(

  <div className='App'>

  <h1>{state}</h1>

  <button onClick={() =>setState("Balaji")}>Change Name</button>

  </div>

 )

}


export default App;



Output: 

The output will be:


Before changing the state


After clicking on the button, the state will be changed to “Balaji”.



  1. useEffect

useeffect in react js is another type of hook in React. This hook allows us to perform side effects on our components.

Some examples of useEffect are: fetching data, directly updating the DOM, and timers.

useEffect accepts two arguments (function and dependency), and the second argument is optional.


useEffect(<function>,<dependency>)

Let see with example: 

import React, { useState, useEffect } from 'react';

function Example() {

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

  useEffect(() => {

    document.title = `You clicked ${count} times`;

  });

  return (

    <div>

      <p>You clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>

        Click me

      </button>

    </div>

  );

}

export default Example;

First, we declare the count state variable, and then we use an effect. We pass a function to the useEffect hook. The function we pass is our effect. Inside the effect, we set the document title using the document.title browser API. When a component is rendered, it remembers the effect we used and then runs the effect after updating the DOM. This happens for every render, and it also includes the first one.


Output:

The output of the above code area is:


Initially, the click is 0 times.


But, after clicking on the button, the number of clicks will be shown.


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...