DEV Community

Srushti Patil
Srushti Patil

Posted on

State of Mind: React useState Made Simple - Part 1

Part 1: What is State? And Why Should I Care?

When you're building an interactive app with React, you want your components to remember stuff.

But React doesn’t just magically remember things like:

  • Whether a button was clicked
  • What the user typed into a field
  • If a modal is open or closed

That’s where state comes in.


🤔 What Is “State”?
Think of the state like your app’s memory.
React provides a way to store values within a component that change over time.

📦 It’s like a mini storage unit inside your component — and when you change what’s inside, React updates the UI automatically!


🧠 Real-World Analogy: Mood Ring
Imagine a React component is like a mood ring.
_
If you're happy, it turns green

If you're sad, it turns blue

If you're excited, it glows purple_

Your mood is the state — it changes based on how you're feeling, and the ring (UI) reacts to it.


🧩 Enter useState()
To give our component a memory, we use a React Hook called useState.

import React, { useState } from 'react';

function MoodRing() {
  const [mood, setMood] = useState('😊');

  return (
    <div>
      <h2>Your mood: {mood}</h2>
      <button onClick={() => setMood('😢')}>Sad</button>
      <button onClick={() => setMood('😄')}>Happy</button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

👀 What’s Happening Here?

const [mood, setMood] = useState('😊');

Enter fullscreen mode Exit fullscreen mode

You're telling React:

  • "Hey, I need a piece of memory called mood"
  • "Set it initially to 😊"
  • "Give me a function setMood to change it"
  • When setMood is called, React updates the value of mood

Re-renders the component with the new mood


🧪 Beginner Tip: Always Use setState
You shouldn’t modify state variables directly:

mood = '😡'; // ❌ Wrong!
setMood('😡'); // ✅ Correct!

Enter fullscreen mode Exit fullscreen mode

Why? Because React won’t know something changed unless you use the setter function (setMood). That’s how React knows it needs to update the UI.


📌 Coming Up in Part 2...
Now that you know what state is, in the next part we’ll explore:

  • Multiple useState calls
  • Storing objects/arrays
  • Best practices and common mistakes

Stay tuned for:
👉 “Part 2: Don’t Be Shy, useState All the Things!”

Top comments (1)

Collapse
 
snehal_p profile image
Snehal Pande

👏👏