DEV Community

Cover image for How I Mastered React useState in One Day
Karthick (k)
Karthick (k)

Posted on

How I Mastered React useState in One Day

Today, I decided to understand the most important hook in React: useState deeply. If you are preparing for an interview or just starting out, useState is the foundation of everything you will build.

Here is how I learned it, broken down into 4 simple examples.

What is useState?

useState is a built-in React Hook that gives functional components their own "memory". Without it, variables disappear when a component re-renders. It returns an array with two things: the current state and a function to update it.

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode
import React, { useState } from 'react';

export default function UseStatePlayground() {
  // 1. Number State (Counter)
  const [count, setCount] = useState(0);

  // 2. String State (Input Tracker)
  const [name, setName] = useState("");

  // 3. Boolean State (Toggle)
  const [isVisible, setIsVisible] = useState(false);

  // 4. Array State (Shopping List)
  const [items, setItems] = useState([]);
  const [inputValue, setInputValue] = useState("");

  const addItem = () => {
    if (inputValue.trim() !== "") {
      setItems([...items, inputValue]); // Spread operator to add to array
      setInputValue(""); // Clear input after adding
    }
  };

  return (
    <div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
      <h2>React useState Practice</h2>

      {/* --- 1. Counter (Number) --- */}
      <div style={{ marginBottom: '20px' }}>
        <h3>1. Counter</h3>
        <p>Count: {count}</p>
        <button onClick={() => setCount(count + 1)}>Add 1</button>
      </div>

      {/* --- 2. Input Tracker (String) --- */}
      <div style={{ marginBottom: '20px' }}>
        <h3>2. Input Tracker</h3>
        <input 
          type="text" 
          value={name} 
          onChange={(e) => setName(e.target.value)} 
          placeholder="Type your name"
        />
        <p>Hello, {name || "stranger"}!</p>
      </div>

      {/* --- 3. Toggle (Boolean) --- */}
      <div style={{ marginBottom: '20px' }}>
        <h3>3. Toggle</h3>
        <button onClick={() => setIsVisible(!isVisible)}>
          {isVisible ? "Hide" : "Show"} Secret
        </button>
        {isVisible && <p>👑 The secret password is: ReactIsAwesome</p>}
      </div>

      {/* --- 4. Array (Shopping List) --- */}
      <div>
        <h3>4. Array List</h3>
        <input 
          type="text" 
          value={inputValue} 
          onChange={(e) => setInputValue(e.target.value)} 
          placeholder="Add an item"
        />
        <button onClick={addItem}>Add</button>
        <ul>
          {items.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)