Skip to main content

Command Palette

Search for a command to run...

useState Examples

Published
•6 min read•View as Markdown
useState Examples

Understanding useState: The Easiest Guide (with Examples)

Hey there! Let's break down React's useState hook in the simplest way possible. Think of it as a way for your component to remember things.

What is State?

Imagine you're playing a video game. Your health points, score, and level - that's your game's state. In React, state is just data that changes over time.

The Basic Idea

// The simplest useState example ever:
const [number, setNumber] = useState(0);

Let's translate this:

  • number = What we're remembering (like your current score)

  • setNumber = How we change it (like pressing buttons)

  • useState(0) = Starting value (starting at 0 points)

Real-Life Example: A Light Switch

Think of a light in your room:

  • It can be ON or OFF (that's the state)

  • The switch changes it (that's the setter function)

Here's the code version:

import React, { useState } from 'react';

function LightBulb() {
  // Step 1: Create state
  // 'isOn' is our state variable (true = ON, false = OFF)
  // 'setIsOn' is how we change it
  // useState(false) means we start with light OFF
  const [isOn, setIsOn] = useState(false);

  return (
    <div>
      {/* Step 2: Show the state */}
      <p>The light is {isOn ? 'ON' : 'OFF'}</p>

      {/* Step 3: Add buttons to change state */}
      <button onClick={() => setIsOn(true)}>
        Turn ON
      </button>

      <button onClick={() => setIsOn(false)}>
        Turn OFF
      </button>

      {/* Toggle button - switches between ON/OFF */}
      <button onClick={() => setIsOn(!isOn)}>
        Toggle Switch
      </button>
    </div>
  );
}

Let's Build a Counter (Step by Step)

Step 1: Import useState

import React, { useState } from 'react';
// We need to import useState before we can use it

Step 2: Create the component

function Counter() {
  // We'll write our state here

  return (
    // We'll show our counter here
  );
}

Step 3: Add state

function Counter() {
  // Create state for our counter
  const [count, setCount] = useState(0);
  // count = current number (starts at 0)
  // setCount = function to change the number

  return (
    <div>
      <p>Count: {count}</p>
      {/* Show the current count */}
    </div>
  );
}

Step 4: Add buttons to change state

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

  return (
    <div>
      <p>Count: {count}</p>

      {/* Button to increase count */}
      <button onClick={() => setCount(count + 1)}>
        Add 1
      </button>

      {/* Button to decrease count */}
      <button onClick={() => setCount(count - 1)}>
        Subtract 1
      </button>

      {/* Reset button */}
      <button onClick={() => setCount(0)}>
        Reset
      </button>
    </div>
  );
}

How State Actually Works (The Magic)

When you use setCount(newValue):

  1. React remembers the new value

  2. React re-renders your component

  3. The count variable gets the new value

  4. Your screen updates to show the new value

Multiple States in One Component

You can have as many states as you need:

function UserForm() {
  // State for name
  const [name, setName] = useState('');

  // State for age
  const [age, setAge] = useState(0);

  // State for subscribe option
  const [isSubscribed, setIsSubscribed] = useState(false);

  return (
    <div>
      <input 
        type="text" 
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Your name"
      />

      <input 
        type="number" 
        value={age}
        onChange={(e) => setAge(Number(e.target.value))}
        placeholder="Your age"
      />

      <label>
        <input 
          type="checkbox"
          checked={isSubscribed}
          onChange={(e) => setIsSubscribed(e.target.checked)}
        />
        Subscribe to newsletter
      </label>

      <div>
        <h3>Your Information:</h3>
        <p>Name: {name || 'Not provided'}</p>
        <p>Age: {age || 'Not provided'}</p>
        <p>Subscribed: {isSubscribed ? 'Yes' : 'No'}</p>
      </div>
    </div>
  );
}

Important Rules to Remember

Rule 1: Never Modify State Directly

// ❌ WRONG - DON'T DO THIS
count = count + 1;

// ✅ CORRECT - ALWAYS DO THIS
setCount(count + 1);

Rule 2: Use Previous State Properly

If you need the old value to calculate the new value:

// Problem: This might not work correctly
setCount(count + 1);
setCount(count + 1); // Uses OLD count value twice

// Solution: Use the function form
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1); // Works perfectly!

Rule 3: Objects/Arrays Need Special Care

const [user, setUser] = useState({ name: 'John', age: 25 });

// ❌ WRONG - Changing directly
user.age = 26; // This won't update the screen!

// ✅ CORRECT - Create a new object
setUser({
  ...user,     // Copy everything from old user
  age: 26      // Change just the age
});

Simple Todo List Example

function SimpleTodo() {
  // State for the list of todos
  const [todos, setTodos] = useState([
    'Learn React',
    'Build a project',
    'Write a blog'
  ]);

  // State for new todo input
  const [newTodo, setNewTodo] = useState('');

  const addTodo = () => {
    if (newTodo.trim() !== '') {
      // Add new todo to the list
      setTodos([...todos, newTodo]);
      // Clear the input
      setNewTodo('');
    }
  };

  const removeTodo = (index) => {
    // Create a new array without the item at index
    const newTodos = todos.filter((_, i) => i !== index);
    setTodos(newTodos);
  };

  return (
    <div>
      <h2>My Todo List</h2>

      {/* Input for new todo */}
      <input
        type="text"
        value={newTodo}
        onChange={(e) => setNewTodo(e.target.value)}
        placeholder="Add a new todo"
      />
      <button onClick={addTodo}>Add</button>

      {/* Display todos */}
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>
            {todo}
            <button onClick={() => removeTodo(index)}>
              Remove
            </button>
          </li>
        ))}
      </ul>

      <p>Total todos: {todos.length}</p>
    </div>
  );
}

Common Mistakes & Fixes

Mistake 1: Forgetting to use the setter function

// ❌ This does nothing
let count = 0;
count = 1;

// ✅ This updates the screen
const [count, setCount] = useState(0);
setCount(1);

Mistake 2: Updating state based on old state incorrectly

// ❌ Might not work as expected
setCount(count + 1);
setCount(count + 1);

// ✅ Always works correctly
setCount(prev => prev + 1);
setCount(prev => prev + 1);

When Should You Use useState?

Use useState when:

  • ✅ You need to remember user input (forms)

  • ✅ You need toggle switches (show/hide)

  • ✅ You need counters or scores

  • ✅ You need to track any changing data

Don't use useState for:

  • ❌ Data that never changes (use regular variables)

  • ❌ Data shared between many components (use Context or props)

Practice Exercise

Try this: Create a simple component that:

  1. Has a button that says "Like"

  2. Shows how many likes you've given

  3. Has a button to reset likes to 0

  4. Changes color when likes are more than 5

Here's a starting point:

function LikeButton() {
  // Your state goes here

  return (
    <div>
      {/* Your JSX goes here */}
    </div>
  );
}

Summary

  1. useState lets components remember things

  2. It gives you two things: current value + function to change it

  3. Always use the setter function to change state

  4. State changes trigger re-renders (screen updates)

  5. You can have multiple states in one component