Logo

dev-resources.site

for different kinds of informations.

Mastering React Hooks: useState and useEffect

Published at
10/9/2024
Categories
react
usestate
useeffect
webdev
Author
jenishdabhi
Categories
4 categories in total
react
open
usestate
open
useeffect
open
webdev
open
Author
11 person written this
jenishdabhi
open
Mastering React Hooks: useState and useEffect

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!

usestate Article's
30 articles in total
Favicon
useState e useEffect
Favicon
Mastering React's useState Hook: The Basics and Advanced Use Cases
Favicon
Understanding useState in TypeScript React
Favicon
A Beginner's Guide to useState in React
Favicon
Mastering React Hooks: useState and useEffect
Favicon
Managing State in react using different method, & understand batching
Favicon
Hooks Behind The Scenes 2, useState!!
Favicon
useState Hook Explained
Favicon
Exploring State Management in React: One-Way Data Binding, State Lift-Up, Prop Drilling, and Handling Complex States
Favicon
Diving into React.js
Favicon
What is useState?
Favicon
Avoiding Common useState() Mistakes in React
Favicon
Simplifying State Management in React with Zustand
Favicon
Having trouble with react component hooks...
Favicon
useState( )
Favicon
Create a modified useState hook to get previous value
Favicon
UseState why?
Favicon
Part 2 - Mastering the useState Hook
Favicon
Part 1 - Getting Started with React Hooks
Favicon
ugly useState
Favicon
Unlocking the Power of React Hooks
Favicon
Mastering 'useState' in React with TypeScript: 5 Different Use-Cases for 'useState'
Favicon
React.useRefăźç†è§Łă‚’ć«ă‚ă‚‹ă‚šă‚Żă‚”ă‚”ă‚€ă‚ș
Favicon
Toggle Feature for a Drop-down list on React using useState();
Favicon
useContext
Favicon
A Beginner's Guide to Using Fetch in React: Making Data Requests Made Easy
Favicon
AlteraçÔes de påginas de forma dinùmica com o UseState
Favicon
Stop using useState for everything
Favicon
useState: la caja de juguetes
Favicon
Detaylı React Hooks Kullanımı: useState

Featured ones: