Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

🟒 BeginnerπŸ”΅ Advanced
πŸ’Ύ Introduction to Stateβš›οΈ Using useState HookπŸ”„ Updating State Correctly🎯 Initial State Values🚫 Common State MistakesπŸ“Š Multiple State VariablesπŸ”— State & RenderingπŸ“ Forms with StateπŸ—οΈ State Structure Best Practices
Reactjs/State/Updating State

πŸ”„ Updating State Correctly β€” Triggering Re-renders

Calling the setter function updates state and tells React to re-render the component. Always create new values instead of modifying the old ones.


🎯 Basic State Updates

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>

πŸ’‘ Immutability: Creating New Values

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>

πŸ”§ Using Previous State

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>
  );
}

πŸ“Š Summary

PatternUse 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

πŸ”‘ Key Takeaways

  • βœ… Call setter function to update state and trigger re-render
  • βœ… Always create new values, don't modify state directly
  • βœ… Use spread operator (`...`) for arrays and objects
  • βœ… Use function form when new state depends on old state
  • βœ… State updates are asynchronous and batched
  • βœ… Each setter call triggers a new re-render

Ready to practice? Challenges | Next: Multiple State Variables


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

Β© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn