Front-end development

Branding & Vision

Web Designer

React Hooks for Dummies: Understanding useState()

React Hooks for Dummies:Understanding useState()

React hooks for dummies: Understanding useState explained in plain English, with clear examples and practical tips for aspiring developers getting started with React.

React JSVanilla JS

Hey there! 👋 As someone with a background in marketing rather than coding, I know firsthand how intimidating React can be. All those technical terms and developer jargon can make your head spin, right? That's why I created this guide - to explain useState() in a way that actually makes sense to normal humans.

If you've ever felt lost in the world of React (I definitely have!), or if technical documentation makes you want to cry, then this guide is for you. Let's break this down into bite-sized, digestible pieces!

What You'll Learn

  • What React Hooks are (in normal person speak!)
  • How useState works (with real-world examples)
  • When to use useState (and when not to)
  • Common mistakes to avoid

*No technical jargon was harmed in the making of this guide* 😉

What Are React Hooks?

Imagine you're building with LEGO blocks. React Hooks are like those special LEGO pieces that have specific powers - they help your regular LEGO pieces do cool things. They're basically pre-built features that React gives us to use in our projects.

Think of Hooks like a Swiss Army knife - each tool has a specific purpose:

  • useState: Your magical notepad (we'll dive deep into this one!)
  • useEffect: Your personal assistant who watches for changes and does tasks for you
  • useContext: The group chat where everyone can share information
  • useReducer: Like useState's big brother who's better at handling complicated stuff
  • useMemo: Your smart friend who remembers solutions to avoid doing the same math twice
  • useCallback: Similar to useMemo, but for remembering functions
  • useRef: Like putting a sticky note on something to find it later

What is useState? (The Magical Notepad)

Remember those magic boards where you could write something, erase it, and write something new? useState is exactly like that for your website! It helps your website remember things and update them when needed.

It looks like this in code:

const [something, setSomething] = useState(startingValue);

Think of it as:

  • `something` - What's currently written on your board
  • `setSomething` - Your special eraser/marker to change what's written
  • `startingValue` - What you write on the board to begin with

How Does useState Work?

Let me explain this like a cooking recipe:

1. Getting Ready to Cook (Initialisation Phase)

  •  You need to set up a new cooking environment (that's your component)
  • Create a special recipe card (React creates a space for your state)
  • Each ingredient measurement gets its own spot on the card

2. Changing the Recipe (Update Phase)

When you want to change an ingredient amount:

  •               React writes the change on a sticky note
  •               Puts that sticky note in a "to-do" pile
  •               Plans to update the recipe soon
  •               If you make multiple changes at once, React groups them together (like changing several ingredients at the same time)

3. Making the Changes (Render Phase)

  •               React goes through all the sticky notes
  •               Figures out the new amounts of everything
  •               Updates the recipe card
  •               Shows everyone the new recipe

4. Finishing Up (Commit Phase)

  •             React actually makes these changes in the kitchen
  •           Cleans up any old ingredients
  •           Sets up the new ingredients

Real-World Examples of useState

Let's look at some examples that actually make sense:

1. A Simple Welcome Message

JSX
import React, { useState } from "react";

function WelcomeMessage() {
  // Think of this like a greeting card where you can change the name
  const [name, setName] = useState("Guest")

  return (
    <div>
      <input 
        value={name}
        onChange = {(e) => setName(e.target.value)}
        placeholder="Type your name"
      />
      <p>Welcome to my website, {name}! 🎉</p>
    </div>
  )
}

2. A Like Button Counter

JSX
function LikeButton() {
  // Just like counting likes on Instagram
  const [likes, setLikes] = useState(0)

  return (
    <div>
      <p>This post has {likes} likes</p>
      <button onClick={() => setLikes(likes + 1)}>♥️ Like</button>
    </div>
  )
}

3. Dark Mode Toggle

JSX
function DarkModeSwitch() {
  // Like a light switch for your website
  const [isDark, setIsDark] = useState(false)

  return (
    <div style={{
      background: isDark ? 'black' : 'white',
      color: isDark ? 'white' : 'black'
    }}>
      <button onClick={() => setIsDark(!isDark)}>
        Switch to {isDark ? '☀️ Light' : '🌙 Dark'} Mode
      </button>
    </div>
  )
}

Common Mistakes (We All Make Them!)

1. Trying to Change Things Directly

// 🚫 Don't do this!

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

user.name = 'Jane'  // This is like trying to edit a photocopy instead of the original

// Do this instead!

setUser({...user, name: 'Jane'})  // This is like making a new copy with the changes

2. Updating Based on Previous Value

// 🚫 This is like trying to count in your head while someone's talking to you

setCount(count + 1)

setCount(count + 1)  // Oops, this won't work right!

// This is like writing down each step

setCount(previousCount => previousCount + 1)

setCount(previousCount => previousCount + 1)  // Much better!

When Should You Use useState?

Use useState when you need to:

  1. Keep track of form inputs (like a contact form)
  2. Toggle things on/off (like a menu or dark mode)
  3. Count things (like items in a shopping cart)
  4. Store temporary information (like what tab is selected)
  5. Handle user interactions (like marking favourites)

When Should You Not Use useState?

Don't use useState when:

  1. You need to share data between lots of components (use Context instead)
  2. You have complex state logic (useReducer would be better)
  3. You're dealing with large amounts of data
  4. You need to update multiple related things at once

Conclusion

useState might seem scary at first, but it's really just a way to help your website remember things - like a digital sticky note system! The key is to:

  • Start simple (don't overthink it!)
  • Use it for one thing at a time
  • Practice with basic examples
  • Don't worry about being perfect

Remember, everyone starts somewhere, and if you're coming from a non-technical background like me, it's totally normal to take time to understand these concepts. Just keep practicing, and it'll start to make sense!

*Stay tuned for more guides where I break down other React concepts into normal human language!* 💪

Questions? Feel free to reach out! And remember - if I can understand this stuff coming from a marketing background, you definitely can too! 🚀

Javi Ductor Peters
Written by Javi Ductor Peters

thespaghetti.dev

Looking for a front-end developer?