Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🪝 What are Hooks🔄 Rules of Hooks🧠 Using useState⚙️ Using useEffect🎣 Custom Hooks📦 Built-in Hooks🔗 Combining Hooks⚡ Hooks Best Practices
Reactjs/Hooks/Using Usestate

🔄 Using useState — Managing Component State with Hooks

useState is the most fundamental Hook. It lets you add state to functional components and update it to trigger re-renders.


🎯 useState Syntax and Basics

Call useState with an initial value. It returns an array with the current state and a function to update it. Use array destructuring to name them clearly.

useState takes one argument: the initial state value. It returns an array with two elements: the current state and a function to update it.

import { useState } from 'react';

function Counter() {
  // Syntax: const [value, setValue] = useState(initialValue)
  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: Different state types

function FormExample() {
  const [text, setText] = useState('');           // String
  const [number, setNumber] = useState(0);        // Number
  const [isVisible, setIsVisible] = useState(true); // Boolean
  const [items, setItems] = useState([]);         // Array
  const [user, setUser] = useState({ id: 1 });   // Object

  return (
    <div>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      <p>Text: {text}</p>
    </div>
  );
}

</details>

💡 Updating State Correctly

When updating state, create new values instead of modifying old ones. For objects and arrays, use spread operator to create new copies.

import { useState } from 'react';

function TodoList() {
  const [todos, setTodos] = useState([]);

  const addTodo = (text) => {
    // Create new array with new item
    setTodos([...todos, { id: Date.now(), text }]);
  };

  const removeTodo = (id) => {
    // Create new array without the item
    setTodos(todos.filter(t => t.id !== id));
  };

  const toggleTodo = (id) => {
    // Map to new array with updated item
    setTodos(todos.map(t =>
      t.id === id ? { ...t, done: !t.done } : t
    ));
  };

  return (
    <div>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>
            {todo.text}
            <button onClick={() => removeTodo(todo.id)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

<details>

<summary>📚 More Examples</summary>

// Example: Using function form of setState

function Counter() {
  const [count, setCount] = useState(0);

  const incrementTwice = () => {
    // Use function form to base update on previous state
    setCount(prev => prev + 1);
    setCount(prev => prev + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementTwice}>+2</button>
    </div>
  );
}

</details>

📊 Summary

ConceptDescription
useStateHook to add state to functional components
Syntax`const [value, setValue] = useState(initial)`
UpdateAlways create new values, don't mutate
Function formUse `setValue(prev => ...)` for dependent updates

🔑 Key Takeaways

  • ✅ useState takes an initial value and returns [state, setter]
  • ✅ Use destructuring to name state variables clearly
  • ✅ Always create new values when updating state
  • ✅ Use spread operator for arrays and objects
  • ✅ Use function form when new state depends on old state
  • ✅ Each component instance gets its own state

Ready to practice? Challenges | Next: Using useEffect


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