React Hooks: useState and useEffect with Real Examples
React Hooks make your functional components powerful by enabling them to manage state and side effects. In this article, we'll cover:
- 🌟 How
useState
adds interactivity - ⏰ How
useEffect
handles side effects like API calls - ✅ Complete, clean examples ready to use
🔁 Counter App using useState
A simple app with buttons to increase, decrease, or reset a count.
import React, { useState } from 'react';
function CounterApp() {
const [count, setCount] = useState(0);
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h2>Simple Counter</h2>
<p style={{ fontSize: '24px' }}>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
<button onClick={() => setCount(count - 1)} style={{ marginLeft: '10px' }}>Decrease</button>
<button onClick={() => setCount(0)} style={{ marginLeft: '10px' }}>Reset</button>
</div>
);
}
export default CounterApp;
🌐 Fetch Users using useEffect
Fetches users from a public API and displays them in a list.
import React, { useState, useEffect } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => {
setUsers(data);
setLoading(false);
})
.catch(error => {
console.error("Error fetching data:", error);
setLoading(false);
});
}, []);
return (
<div style={{ padding: '20px' }}>
<h2>User List</h2>
{loading ? (
<p>Loading users...</p>
) : (
<ul>
{users.map(user => (
<li key={user.id}>
<strong>{user.name}</strong> - {user.email}
</li>
))}
</ul>
)}
</div>
);
}
export default UserList;
⏱️ Timer using useEffect
+ useState
This timer starts, pauses, and resets using buttons and intervals.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
const [isRunning, setIsRunning] = useState(false);
useEffect(() => {
let interval = null;
if (isRunning) {
interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
} else if (!isRunning && seconds !== 0) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isRunning, seconds]);
return (
<div style={{ textAlign: 'center', marginTop: '40px' }}>
<h2>React Timer</h2>
<p style={{ fontSize: '24px' }}>Elapsed: {seconds}s</p>
<button onClick={() => setIsRunning(true)}>Start</button>
<button onClick={() => setIsRunning(false)} style={{ marginLeft: '10px' }}>Pause</button>
<button onClick={() => { setSeconds(0); setIsRunning(false); }} style={{ marginLeft: '10px' }}>Reset</button>
</div>
);
}
export default Timer;
🎯 Conclusion
Using useState
and useEffect
, we can add interactivity and control side effects without writing class components. These hooks are now the standard way to build modern React apps.
0 Comments