
ReactJS
Calling the setter function updates state and tells React to re-render the component. Always create new values instead of modifying the old ones.
Call the setter function with a new value. React will update the state and re-render the component automatically.
State updates are asynchronous. React batches multiple updates together for performance. Always pass a new value to the setterβdon't modify the old state directly.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(0)}>
Reset
</button>
</div>
);
}<details>
<summary>π More Examples</summary>
// Example: Updating different data types
function Form() {
const [name, setName] = useState('');
const [items, setItems] = useState([]);
const [user, setUser] = useState({ id: 1, name: 'John' });
const addItem = () => {
// For arrays, create a new array
setItems([...items, 'New item']);
};
const updateUser = () => {
// For objects, spread and update
setUser({ ...user, name: 'Jane' });
};
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={addItem}>Add Item</button>
<button onClick={updateUser}>Change Name</button>
</div>
);
}</details>
Never directly modify arrays or objects in state. Create new ones instead. This is called immutability and helps React track changes.
import { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React', done: false },
]);
const toggleTodo = (id) => {
// β WRONG: Don't modify the array directly
// todos[0].done = true;
// β
CORRECT: Create a new array
setTodos(
todos.map(todo =>
todo.id === id ? { ...todo, done: !todo.done } : todo
)
);
};
return (
<ul>
{todos.map(todo => (
<li key={todo.id} onClick={() => toggleTodo(todo.id)}>
{todo.text}
</li>
))}
</ul>
);
}<details>
<summary>π More Examples</summary>
// Example: Adding and removing items
function ShoppingList() {
const [items, setItems] = useState(['Milk', 'Bread']);
const addItem = (newItem) => {
// Create new array with new item
setItems([...items, newItem]);
};
const removeItem = (index) => {
// Create new array without the item
setItems(items.filter((item, i) => i !== index));
};
return (
<div>
<ul>
{items.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
<button onClick={() => addItem('Eggs')}>Add</button>
</div>
);
}</details>
When you need to calculate the new state based on the old state, pass a function to the setter. It receives the previous state and returns the new state.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
// Pass a function to access previous state
setCount(prevCount => prevCount + 1);
};
const incrementTwice = () => {
// This is safer than using count directly
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+1</button>
<button onClick={incrementTwice}>+2</button>
</div>
);
}| Pattern | Use Case |
|---|---|
| `setValue(newValue)` | Simple value updates |
| `setValue(prevValue => newValue)` | Based on previous state |
| `setArray([...array, newItem])` | Add to array |
| `setObject({ ...object, key: value })` | Update object property |
Ready to practice? Challenges | Next: Multiple State Variables
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward