Notes
Notes - notes.io |
What is useState?
useState is a React hook that allows functional components to have local state.
Before hooks, state was only available in class components.
useState preserves the state between renders.
Syntax:
jsx
Copy
Edit
const [state, setState] = useState(initialValue);
state → Holds the current value of the state.
setState → Function to update the state.
initialValue → The initial state value (can be a number, string, object, array, or function).
Example 1: Counter using useState
jsx
Copy
Edit
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0); // Initial state = 0
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
export default Counter;
Clicking the button updates the count state using setCount(), causing the component to re-render.
Updating State Correctly
1. Functional Updates (When Using Previous State)
If the new state depends on the old state, always use the function form:
jsx
Copy
Edit
setCount(prevCount => prevCount + 1);
Example 2: Correct Way to Update State
jsx
Copy
Edit
<button onClick={() => setCount(prevCount => prevCount + 1)}>
Increment
</button>
This ensures that React processes updates correctly, especially with asynchronous state updates.
2. Updating State with Objects
jsx
Copy
Edit
const [user, setUser] = useState({ name: "Bhavik", age: 20 });
const updateAge = () => {
setUser(prevUser => ({ ...prevUser, age: prevUser.age + 1 }));
};
The spread operator ...prevUser ensures that other properties remain unchanged.
2. useEffect Hook (Handling Side Effects in React)
What is useEffect?
useEffect allows us to handle side effects in functional components.
Side effects include:
Fetching data from an API
Subscribing to events
Updating the DOM manually
Running code after every render
useEffect runs after the component renders.
Syntax:
jsx
Copy
Edit
useEffect(() => {
// Side effect logic
}, [dependencies]);
First Argument (callback function): Runs after render.
Second Argument (dependencies array, optional):
[] (empty array) → Runs only once (like componentDidMount in class components).
[someState] → Runs when someState changes.
No dependency → Runs after every render.
Example 3: useEffect Without Dependencies (Runs After Every Render)
jsx
Copy
Edit
import React, { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Component rendered! Count: ${count}`);
});
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Every time count updates, the effect runs.
Example 4: useEffect with Dependencies (Runs When State Changes)
jsx
Copy
Edit
useEffect(() => {
console.log(`Count changed: ${count}`);
}, [count]); // Runs only when count changes
The effect runs only when count updates.
Example 5: useEffect Running Once (componentDidMount Equivalent)
jsx
Copy
Edit
useEffect(() => {
console.log("Component mounted!");
return () => {
console.log("Component unmounted!");
};
}, []);
Runs only once when the component mounts.
The cleanup function (return () => {}) runs when the component unmounts.
Example 6: Fetching Data using useEffect
jsx
Copy
Edit
import React, { useState, useEffect } from "react";
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(json => setData(json));
return () => console.log("Cleanup runs when component unmounts.");
}, []);
return (
<ul>
{data.slice(0, 5).map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default DataFetcher;
Fetches data when the component mounts.
Cleanup runs when the component unmounts.
Comparison of useState vs. useEffect
Feature useState useEffect
Purpose Manages state Handles side effects
Runs on State updates Component render/mount/update/unmount
Dependency N/A Optional dependency array
Returns [state, setState] Nothing
Cleanup No Yes (optional cleanup function)
Best Practices for useState and useEffect
✅ Use functional updates (setState(prev => ...)) when updating state based on the previous state.
✅ Minimize useEffect dependencies to avoid unnecessary renders.
✅ Always clean up effects (e.g., remove event listeners, cancel API calls).
✅ Avoid unnecessary re-renders by optimizing dependencies in useEffect.
✅ Keep useState and useEffect logic separate for maintainability.
Key Takeaways
useState is used to store and update values in functional components.
useEffect is used to handle side effects such as API calls, DOM updates, and event listeners.
useEffect can run on every render, only once, or when dependencies change.
Always clean up side effects when needed to prevent memory leaks
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team
