</>
Skip to content
React lessons (18/47)

React — useState

Basic useState

import { useState } from 'react';

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

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>+1</button>
            <button onClick={() => setCount(count - 1)}>-1</button>
        </div>
    );
}

useState with Initial Value

function User() {
    const [user, setUser] = useState({
        name: 'John',
        age: 25,
        email: 'john@example.com'
    });

    return (
        <div>
            <p>Name: {user.name}</p>
            <p>Age: {user.age}</p>
        </div>
    );
}

Updating State

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

    // Direct update
    const increment = () => setCount(count + 1);

    // Functional update (recommended)
    const incrementByFive = () => {
        setCount(prevCount => prevCount + 5);
    };

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={increment}>+1</button>
            <button onClick={incrementByFive}>+5</button>
        </div>
    );
}

useState with Objects

function UserForm() {
    const [user, setUser] = useState({
        name: '',
        email: '',
        age: 0
    });

    const handleChange = (e) => {
        const { name, value } = e.target;
        setUser(prev => ({
            ...prev,
            [name]: value
        }));
    };

    return (
        <form>
            <input
                name="name"
                value={user.name}
                onChange={handleChange}
            />
            <input
                name="email"
                type="email"
                value={user.email}
                onChange={handleChange}
            />
            <input
                name="age"
                type="number"
                value={user.age}
                onChange={handleChange}
            />
        </form>
    );
}

useState with Arrays

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

    const addTodo = () => {
        if (input.trim()) {
            setTodos([...todos, { id: Date.now(), text: input }]);
            setInput('');
        }
    };

    const deleteTodo = (id) => {
        setTodos(todos.filter(todo => todo.id !== id));
    };

    return (
        <div>
            <input
                value={input}
                onChange={(e) => setInput(e.target.value)}
            />
            <button onClick={addTodo}>Add</button>
            <ul>
                {todos.map(todo => (
                    <li key={todo.id}>
                        {todo.text}
                        <button onClick={() => deleteTodo(todo.id)}>
                            Delete
                        </button>
                    </li>
                ))}
            </ul>
        </div>
    );
}

Mini Practice

Write React code that:

  1. Uses useState for simple state
  2. Updates state with functional update
  3. Manages object state
  4. Manages array state

Up Next

Next: Learn about useEffect hook.

Related Topics

Frequently Asked Questions about useState

What is useState in React?

useState is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn useState?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn useState.

Why is useState important in React?

useState is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.