Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 20, 2022 07:14 am GMT

What are Hooks in React JS

What are hooks in React JS ?

Hooks are the new addition in React 16.8. They let you use state and other react features without writing a class.
Using hooks in react class components are no longer needed.

How to use Hook in react ?

To use any react hook you must import it from react library.

There are Three Main Hooks in React JS:

  1. useState
  2. useEffect
  3. useContext

useState Hook

The React useState Hook allows us to track the state in a functional component
State generally refers to data or properties that need to be tracked in an application.

import { useState } from 'react';

we initialize useState by passing the default value into the function. useState accepts an initial state and returns two values

  1. The current state
  2. Function to change the state.
import { useState } from 'react'function Fun() {    const [name, setName] = useState("state hook");}

useState Example :

useEffect Hook

useEffect hook allows you to perform side effects in your functional components.

What does side effects mean? like fetching data from an API, updating DOM, timers etc....

useEffect two parameters in which second one is optional.
useEffect(<function>,<dependency>);

If you do not pass second parameter useEffect will run on every render.
If you pass an empty array [] useEffect will run only on first render.
If you pass any prop or state as dependency then useEffect will run on first render and every time when dependency changes.

useEffect Example


Original Link: https://dev.to/vamsitupakula_/what-are-hooks-in-react-js-4ejc

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To