DEV Community

Selahaddin Osmanoglu
Selahaddin Osmanoglu

Posted on

Part 3: State and Event Handling – Making Components Interactive

Welcome to Part 3 of our beginner React series!

So far, you've learned about components and props. But what if your app needs to remember something or respond to user actions?

That’s where state and event handling come in.


🧠 What Is State?

State is data that a component remembers between renders.

For example:

  • A counter that increases
  • A button that toggles dark mode
  • A form input that shows what the user typed

React provides a built-in hook called useState to manage this.


✨ Example: Counter Component

Let’s build a simple counter to demonstrate how useState works.

Counter.jsx

import { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times.</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Key Concepts:

  • useState(0) sets the initial value of count to 0.
  • setCount is the function that updates count.
  • Changing state causes the component to re-render.

🎯 What Is Event Handling?

Event handling means responding to things like:

  • Button clicks
  • Form submissions
  • Mouse movement
  • Keyboard input

In React, you attach handlers like this:

<button onClick={handleClick}>Click</button>
Enter fullscreen mode Exit fullscreen mode

Where handleClick is a function you define.


✅ Example: Show a Message on Button Click

import { useState } from 'react';

function ClickMessage() {
  const [message, setMessage] = useState('');

  function handleClick() {
    setMessage('You clicked the button!');
  }

  return (
    <div>
      <button onClick={handleClick}>Click me</button>
      <p>{message}</p>
    </div>
  );
}

export default ClickMessage;
Enter fullscreen mode Exit fullscreen mode

🔁 Conditional Rendering with State

You can conditionally show parts of the UI based on state:

{isVisible && <p>Hello, world!</p>}
Enter fullscreen mode Exit fullscreen mode

Or use a ternary:

<p>{isLoggedIn ? 'Welcome!' : 'Please log in'}</p>
Enter fullscreen mode Exit fullscreen mode

✍️ Challenge for You

Create a component called LikeButton:

  • It should show “You liked this!” after clicking.
  • It should toggle between "Like" and "Unlike" buttons.
  • Try adding a count of likes if you’re feeling adventurous!

✅ Summary

  • useState lets components remember and update data.
  • Updating state triggers a re-render.
  • Event handlers (like onClick) let you respond to user actions.
  • You can conditionally render JSX based on state values.

🔜 What’s Next?

In Part 4, we’ll explore how to render lists of data using .map() and learn how React keeps track of changes with keys.

You're doing great — now your components are interactive! 🎉

Top comments (0)