What Are Hooks In React.js/Next.js? Understand Useeffect And Usestate Hooks.
- Posted on October 1, 2023
- By MmantraTech
- 181 Views
In React.js, useState
and useEffect
are fundamental hooks introduced in React version 16.8 for managing state and side effects in functional components, respectively.
React hooks are a feature introduced in React version 16.8 that allows developers to use state and other React features without writing a class. They are functions that enable developers to "hook into" React state and lifecycle features from function components. React hooks provide a more readable and understandable way to manage state, side-effects, and other React features, making it easier to work with functional components.
Hooks are functions that let developers "hook into" React state and lifecycle features from function components. They do not work inside classes. Hooks are functions that let developers "hook into" React state and lifecycle features from function components. They don't work inside classes. By using hooks, developers can use state and other React features without writing a class.
-iKE5G4mocB.png)
In short, we can say that Hooks are javascript functions which are hooked in React.js Component as per need generally to persist State and avoiding side effects which happend during re-render the component.
React.js provides some popular hooks which are as below:
- useState
- useEffect
- useContext
- useReducer
- useCallback
- useMemo
- useRef
- useLayoutEffect
- useDebugValue:
But in this article I am going to explain most usable hooks "useState" and "useEffect". I recomment you to understand React Components lifecylce here (article link ) as to understand hooks like useState and useEffect require understanding of lifecylce else you can proceed if you already know.
---------------- Why useState Hook----------------------
Ok.First question which arise in our mind that what is the requirement of "useState" hook. The answer is very simple because functional component in React.js ( or Next.js) is stateless. It means you can not manage state of a variable as you can do in Class component using this.state. Ok. Let's understand whole scenario practically.
if you check below code in App.jsx ( I modified the code ) then could you imagine that incrementing the variable "i" will have effect on UI part. Remember "i" is a simple variable.
import { useEffect, useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
function App() {
let i = 1;
const handleF1 = () => {
i = i + 1;
// console.log(i)
};
return (
<>
<div>
Normal Variable i = {i} <br />
<button onClick={handleF1}>Increment in i </button>
</div>
<UserInfo i={i} />
</>
);
}
function UserInfo({ i }) {
return (
<>
<p>User Details</p>
x=={i}
</>
);
}
export default App;
Ok. The above example when you run and increment the value of "i" will not affect UI part as value will be remain 1. It is so UI has no synchronization with updated variable. That is problem with Funcitonal Component as they do not manage stae of variales. So that what is solution . Here comes Hook "useState"
useState
is a function which is imported From React.The useState
hook allows you to add state to functional components. It returns a stateful value and a function to update it.
Let's see modified version of above example and I am sure you will get the ideas of useState
import { useEffect, useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
function App() {
const [x, setX] = useState(1);
let i=1
const handleF1=()=>{
i=i+1;
// console.log(i)
}
const handleF2=()=>{
setX(x+1)
console.log(x)
}
useEffect(()=>{
console.log("useEffect==",x)
},[x])
return (
<>
<div>
<p>This component rendered {x} times</p>
Normal Variable i = {i} <br/>
State Variable x ={x}<br/>
<button onClick={handleF1} >Increment in i </button>
<button onClick={handleF2}>Increment in x </button>
<UserInfo x={x}/>
{/* <ProductInfo /> */}
</div>
</>
);
}
function UserInfo(props) {
return (
<>
<p>User Details</p>
x=={props.x}
</>
);
}
function ProductInfo() {
return (
<>
<p>Product Details</p>
</>
);
}
export default App;
In this example, useState(1)
initializes the x
state variable with a value of 1. The setX
function updates the x
state variable.
Syntax:
const [x, setX] = useState(1);
The above reminds you about getter and setter concept. x is a variable and we are assigning some initial value using useState
.setX is a setter function to update the value of x.
---------------- Why useEffect Hook-------------------
Ok guys So far so good. This Hook is a very interesting one. I honestly agree that if a coder does not know about the problem with useState (prevState and next renderState ) and side effect of functional component then He can not understand the requirement of useEffect.
The useEffect
hook performs side effects in functional components. It is similar to componentDidMount
, componentDidUpdate
, and componentWillUnmount
in class components.
Basically useEffect is like a trigger which can be executed on the reaction of lifecycle of React Components. UseEffect Hooks eliminates the requirement of above lifecycle elements. Just because of introducing Hooks in React functional components React js official website has accepted to work with functional components avoiding Class components.
Let's understand the problem with useState and Re-rendering in functional component. The feaute of useState hook is when update state of a variable then functional component renders itself again and show updated rendered value to UI ( JSX ). So basically there are two things preState and next rendered state (current state). Let check out below example and you will understand visually.
I hope most of things you have already got. But I explain here to synch things. As you can see when you increment the state variable "x" UI is updated but x value in scope of function does not know the updated state as function component already re-rendered. In next re-rendered you can get the updated value. But mostly time we need to take decision on custom function as soon as you update the state . You can not wait for full re-rendered the functional component. It means when ComponentDidMount is called ( taking ClassComponent ex.) you want to update some values in database. So you need someone who can be triggered as soon as state is changed in custom function. Here comes Hook "useEffect". It is top level hook which can be managed as per requirement. You can control "useEffect" that while re-rendering the component you need to perform some operations once, everytime or the dependency of a particular state variable.
Syntax
useEffect(()=>
{
console.log("useEffect==",x)
},[x])
There are two parameters in useEffect Hook
1) Callback function
2) Dependency array
Scenario 1:
You want to perform operation while re-rendering functional component. As you can see we have remove dependency array.
useEffect(()=>
{
console.log("useEffect==",x)
})
Scenario 2:
You want to perform operation only once at every re-render in functional component. You need to put blank array
useEffect(()=>
{
console.log("useEffect==",x)
},[])
Scenario 3:
You want to perform operation on change of a particlar state variable while re-rendering functional component. You need to put array with dependency variable.
useEffect(()=>
{
console.log("useEffect==",x)
},[x])
Use Case Scenario.
Suppose you need to call user's data from some api as soon as x value becomes "3". Then your code in useEffect will be like below
useEffect(()=>
{
if(x==3)
{
const data = await fetch("http://localhost:3005/api/razorpay");
const { order } = await data.json();
}
},[x])
By using hooks like useState
and useEffect
, developers can create more functional and readable components without the need for class-based components, making React code more concise and easier to maintain.
Write a Response