JSTAcademy
0 XP
Dashboard
Crash Courses
useState & State Management
10 min
Basic+150 XP
Crash Courses · Basic

useState & State Management

Add interactivity to components with local state using the useState hook.
10 min read+150 XP on completionCert: React Crash Course
Tap any word in the text below to start reading from there.

useState & State Management

useState adds local state to function components. Every time state changes, the component re-renders.

Basic useState

import { useState } from 'react'

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

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

Functional Updates (When State Depends on Previous)

// WRONG — may use stale value in async situations
setCount(count + 1)

// CORRECT — always uses latest value
setCount(prev => prev + 1)

// When multiple updates in a row
function addThree() {
  setCount(prev => prev + 1)
  setCount(prev => prev + 1)
  setCount(prev => prev + 1)
  // count goes up by 3
}

State with Objects

interface FormState {
  name: string
  email: string
  message: string
}

function ContactForm() {
  const [form, setForm] = useState<FormState>({
    name: '', email: '', message: ''
  })

  const handleChange = (field: keyof FormState) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
      setForm(prev => ({ ...prev, [field]: e.target.value }))

  return (
    <form>
      <input value={form.name} onChange={handleChange('name')} placeholder="Name" />
      <input value={form.email} onChange={handleChange('email')} placeholder="Email" />
    </form>
  )
}

State with Arrays

const [items, setItems] = useState<string[]>([])

// Add
setItems(prev => [...prev, newItem])

// Remove
setItems(prev => prev.filter(item => item !== targetItem))

// Update
setItems(prev => prev.map(item => item === old ? updated : item))

Never push to an array in state directly create a new array.

0%