
Published by Ram Karan on June 2023
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
The useState is a Hook (we'll talk about what this means in a moment) that allows you to add React state to function components. Here is an example:
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the above example, the useState hook takes the initial state as a parameter (0 in this case) and returns an array containing the current state and a function to update it. We can then use the setCount function to update the state.
The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API. Here is an 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>
);
}
Author:

Ram Karan
MERN Stack Developer