⚙️ What Is “State” in React?
State is data that changes over time in your component — like user input, counters, form values, API data, etc.
When you update state, React automatically re-renders the component to reflect the new data.
🪣 1. useState — For Managing Local State
🧩 Syntax
const [state, setState] = useState(initialValue);
state → the current value
setState → function to update it
initialValue → the starting state
🧠 Example: Counter
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // initial value is 0
return (
<div>
<p>You clicked {count} times!</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Counter;
✅ When you click the button, count updates → React re-renders the component → UI shows new count.
🔁 2. useEffect — For Side Effects
🧩 What’s a “side effect”?
Anything that affects something outside the component:
Fetching data from an API
Updating the document title
Setting up a timer
Subscribing/unsubscribing to events
🧠 Syntax
useEffect(() => {
// side effect code
return () => {
// optional cleanup (runs when component unmounts or dependencies change)
};
}, [dependencies]);
The callback runs after render.
The dependency array controls when it runs.
⚡ 3. useEffect Examples
🧩 Example 1: Run Once (on Mount)
Like componentDidMount in class components.
import { useEffect } from 'react';
function App() {
useEffect(() => {
console.log('App mounted!');
}, []); // empty array → runs only once
}
🧩 Example 2: Run on State Change
React re-runs the effect whenever a dependency changes.
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Count changed: ${count}`);
}, [count]); // runs every time count updates
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
🧩 Example 3: Fetch Data from an API
useEffect is perfect for async calls (just remember: the callback itself can’t be async).
import { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
async function fetchUsers() {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await res.json();
setUsers(data);
}
fetchUsers();
}, []); // run once when component mounts
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
🧩 Example 4: Cleanup (like componentWillUnmount)
Cleanup runs before the effect re-runs or when the component unmounts.
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
// cleanup
return () => {
clearInterval(timer);
};
}, []); // run once
🧠 Summary Table
Hook Purpose Runs When Returns
useState Manage local, reactive data On component render [state, setState]
useEffect Handle side effects After render / when dependencies change Optional cleanup function
🚀 Common Pattern
function Example() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadData() {
const res = await fetch('/api/data');
const json = await res.json();
setData(json);
setLoading(false);
}
loadData();
}, []); // run once
if (loading) return <p>Loading...</p>;
return <div>{JSON.stringify(data)}</div>;
}
Learn Full Stack JAVA Course in Hyderabad
Read More
React vs Angular: Which One to Learn?
Angular Basics for Full Stack Java Developers
Introduction to React for Java Developers
How to Use Components in React
Visit Our Quality Thought Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments