Skillversitas

useState Hook

Declaring State with useState

useState is the basic hook for storing and updating local data within a component.

import React, { useState } from 'react';

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

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

Initial State

State can be initialized with a static value or a function.

// Static value
const [name, setName] = useState('John');

// A function for a complex initial value (lazy initialization)
const [items, setItems] = useState(() => {
  const saved = localStorage.getItem('items');
  return saved ? JSON.parse(saved) : [];
});

Setter Function

The setter accepts a new value or an update function.

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

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

  // Update function (recommended for updates based on the previous value)
  const incrementPrev = () => setCount(prev => prev + 1);

  return <button onClick={incrementPrev}>{count}</button>;
}

Asynchronous State Updates

State updates are not applied immediately. React groups updates for batching.

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

  const handleClick = () => {
    setCount(count + 1);
    console.log(count); // Still shows the old value!
    // The new value is available on the next render
  };

  return <button onClick={handleClick}>{count}</button>;
}

Multiple State

We can declare multiple state values in a single component.

function UserForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [age, setAge] = useState(0);

  return (
    <form>
      <input value={name} onChange={e => setName(e.target.value)} placeholder="Name" />
      <input value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" />
      <input type="number" value={age} onChange={e => setAge(Number(e.target.value))} />
    </form>
  );
}

Form Input Example

function LoginForm() {
  const [formData, setFormData] = useState({ username: '', password: '' });

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

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Login:', formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="username" value={formData.username} onChange={handleChange} />
      <input name="password" type="password" value={formData.password} onChange={handleChange} />
      <button type="submit">Log In</button>
    </form>
  );
}

Comparison of Update Methods

Method Example When to Use
Direct value setCount(5) Value does not depend on a previous one
Update function setCount(prev => prev + 1) Update based on the previous value

useState is the foundation of state management in React. Next we will study useEffect to handle side effects.