Mastering React Hooks: useState and useEffect

Jenish Dabhi - Oct 9 - - Dev Community

In React, useState and useEffect are two important hooks that allow you to manage state and perform side effects in functional components. Here's an explanation of each and an example:

useState: useState is a hook that allows you to add state to your functional components. It returns an array with two elements: the current state value and a function that lets you update it.

import React, { useState } from ‘react’;

function Counter() {
// Declare a state variable named ‘count’ with an initial value of 0
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
{/* onClick, call setCount to update the ‘count’ state */}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Enter fullscreen mode Exit fullscreen mode

In this example, useState is used to declare a state variable count with an initial value of 0. The setCount function is used to update the state when the button is clicked.

useEffect: useEffect is a hook that enables you to perform side effects in your functional components. It is similar to componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components.

import React, { useState, useEffect } from ‘react’;

function DataFetcher() {
const [data, setData] = useState(null);

// useEffect is used for data fetching and side effects
useEffect(() => {
// Function inside useEffect is the effect itself
const fetchData = async () => {
try {
const response = await fetch(‘https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error(‘Error fetching data:’, error);
}
};

// Call the fetchData function
fetchData();

// Optionally, you can return a cleanup function
// This cleanup function runs when the component is unmounted
return () => {
// Perform cleanup (if needed)
};
}, []); // The empty dependency array means this effect runs once after the initial render

return (
<div>
{data ? (
<p>Data fetched: {JSON.stringify(data)}</p>
) : (
<p>Loading…</p>
)}
</div>
);
}
Enter fullscreen mode Exit fullscreen mode

In this example, useEffect is used to fetch data from an API when the component mounts. The effect runs once after the initial render due to the empty dependency array ([]). If you specify dependencies in the array, the effect will run whenever those dependencies change.

Thank you for reading.
Happy coding!

. . .
Terabox Video Player