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:
- useState π
- useEffect π
- 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
- The current state
- 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
Top comments (2)
Well articulated. Thank you for sharing
Thank You