DEV Community

Cover image for What are Hooks in React JS
Vamsi Krishna
Vamsi Krishna

Posted on

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';
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
jamesoyanna profile image
James Oyanna

Well articulated. Thank you for sharing

Collapse
 
vamsitupakula_ profile image
Vamsi Krishna

Thank You