Tag: UI State

  • Visualizing common React useState use cases

    useState is essential for managing state in React. This guide covers its use with primitives, objects, arrays, and computed values through practical examples.


    🛠️ Understanding useState

    The useState hook is a fundamental tool for managing state in React components. It allows you to store and update values, triggering re-renders when state changes. Here’s a breakdown of common use cases.

    Basic Syntax:

    const [state, setState] = useState(initialValue);
    • state: Current state value
    • setState(newValue): Function to update the state and trigger re-render
    • initialValue: Default state value

    Visualizing useEffect

    1️⃣ Primitive State (Numbers, Strings, Booleans)

    Counter (Numbers)

    import { useState } from "react";
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }

    Toggle Button (Boolean)

    function ThemeToggle() {
      const [isDarkMode, setIsDarkMode] = useState(false);
    
      return (
        <button onClick={() => setIsDarkMode(!isDarkMode)}>
          {isDarkMode ? "🌙 Dark Mode" : "☀️ Light Mode"}
        </button>
      );
    }

    Input Fields (Strings)

    function InputField() {
      const [username, setUsername] = useState("");
    
      return (
        <input
          type="text"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          placeholder="Enter username"
        />
      );
    }

    2️⃣ Object & Array State

    Form State (Object)

    function FormExample() {
      const [form, setForm] = useState({ name: "", email: "" });
    
      return (
        <div>
          <input
            type="text"
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
            placeholder="Name"
          />
          <input
            type="email"
            value={form.email}
            onChange={(e) => setForm({ ...form, email: e.target.value })}
            placeholder="Email"
          />
        </div>
      );
    }

    To-Do List (Array)

    function TodoList() {
      const [todos, setTodos] = useState([{ id: 1, text: "Learn React", completed: false }]);
    
      const addTodo = () => {
        setTodos([...todos, { id: Date.now(), text: "New Task", completed: false }]);
      };
    
      return (
        <div>
          <ul>
            {todos.map(todo => (
              <li key={todo.id}>{todo.text}</li>
            ))}
          </ul>
          <button onClick={addTodo}>Add Task</button>
        </div>
      );
    }

    3️⃣ Derived & Computed State

    Filtering & Sorting Data

    function FilterList() {
      const [query, setQuery] = useState("");
      const items = ["Apple", "Banana", "Cherry", "Date"];
    
      const filteredItems = items.filter(item => item.toLowerCase().includes(query.toLowerCase()));
    
      return (
        <div>
          <input type="text" placeholder="Search..." onChange={(e) => setQuery(e.target.value)} />
          <ul>
            {filteredItems.map(item => <li key={item}>{item}</li>)}
          </ul>
        </div>
      );
    }

    4️⃣ UI & Interaction State

    Modals & Popups

    function ModalExample() {
      const [isOpen, setIsOpen] = useState(false);
    
      return (
        <div>
          <button onClick={() => setIsOpen(true)}>Open Modal</button>
          {isOpen && (
            <div className="modal">
              <p>Modal Content</p>
              <button onClick={() => setIsOpen(false)}>Close</button>
            </div>
          )}
        </div>
      );
    }

    5️⃣ Performance & Optimization

    Debounced State

    function DebouncedSearch() {
      const [query, setQuery] = useState("");
      const [debouncedQuery, setDebouncedQuery] = useState("");
    
      useEffect(() => {
        const timeout = setTimeout(() => setDebouncedQuery(query), 500);
        return () => clearTimeout(timeout);
      }, [query]);
    
      return (
        <input type="text" onChange={(e) => setQuery(e.target.value)} placeholder="Debounced Search..." />
      );
    }

    📈 Summary

    Mastering useState is essential for building interactive React applications. By structuring state into primitives, objects, computed values, UI state, and performance optimizations, you can create efficient and scalable applications.