State & Events

Learn how state and events make React applications interactive.

State and Event Handling in React

Modern websites are interactive. Buttons can be clicked, forms can be filled, menus can open, and counters can increase. React makes these interactions possible using two important concepts: state and event handling.

State allows a component to store and update data, while event handling lets React respond to user actions such as clicks, typing, or form submissions.

These two concepts work together to create dynamic and interactive applications.

What is State?

State is a built-in React feature used to store information that can change over time.

Whenever the state changes, React automatically updates the user interface to display the latest information.

Real-World Example

Imagine a light switch in your room. The light has two possible states:

  • ON
  • OFF

When you press the switch, the state changes, and the light updates immediately. React state works in a similar way. When the stored data changes, React automatically updates the screen.

Why Do We Need State?

Without state, React components would always display the same information.

State allows components to:

  • Count button clicks
  • Show or hide content
  • Store form input
  • Display notifications
  • Update shopping carts
  • Change themes
  • Track login status

State makes React applications interactive.

Creating State with useState

In modern React, state is created using the useState Hook.

javascript
import { useState } from "react";

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

  return <h2>Count: {count}</h2>;
}

Explanation

  • useState(0) creates a state variable with an initial value of 0.
  • count stores the current value.
  • setCount() updates the value.
  • Whenever setCount() is called, React automatically updates the displayed value.

Updating State

State should always be updated using its setter function.

javascript
import { useState } from "react";

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

Output

Each time the button is clicked:

text
Count: 1
Count: 2
Count: 3
...

React automatically refreshes the displayed number without reloading the page.

What is Event Handling?

An event is an action performed by the user.

Examples include:

  • Clicking a button
  • Typing in a textbox
  • Moving the mouse
  • Submitting a form
  • Pressing a keyboard key

Event handling means telling React what to do when one of these events happens.

Handling a Click Event

One of the most common events is a button click.

javascript
function App() {
  function showMessage() {
    alert("Button Clicked!");
  }

  return (
    <button onClick={showMessage}>
      Click Me
    </button>
  );
}

Explanation

  • onClick is a React event.
  • When the button is clicked, the showMessage() function runs.
  • The browser displays an alert message.

Combining State and Events

State and event handling are often used together.

javascript
import { useState } from "react";

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

  function increaseCount() {
    setCount(count + 1);
  }

  return (
    <div>
      <h2>{count}</h2>
      <button onClick={increaseCount}>
        Increase
      </button>
    </div>
  );
}

How It Works

  • The state starts with 0.
  • The user clicks the button.
  • The click event calls increaseCount().
  • setCount() updates the state.
  • React automatically updates the number on the screen.

This automatic update is one of React's biggest advantages.

Handling Input Fields

State is commonly used with forms.

javascript
import { useState } from "react";

function UserForm() {
  const [name, setName] = useState("");

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

      <h2>Hello, {name}</h2>
    </div>
  );
}

Explanation

  • The user types into the input field.
  • The onChange event runs whenever the text changes.
  • setName() saves the latest value in the state.
  • React updates the greeting immediately.

Common React Events

React provides many built-in events.

text
Event         Description
onClick       Triggered when a user clicks an element.
onChange      Triggered when the value of an input changes.
onSubmit      Triggered when a form is submitted.
onMouseOver   Triggered when the mouse moves over an element.
onKeyDown     Triggered when a keyboard key is pressed.

These events help create responsive and interactive user interfaces.

Best Practices

When working with state and events:

  • Always update state using its setter function.
  • Never modify state directly.
  • Keep state only where it is needed.
  • Give event handler functions meaningful names.
  • Keep event handling code simple and easy to read.
  • Store only the data your component needs.

Following these practices makes your code cleaner and easier to maintain.

Real-World Example

Imagine you are building an online shopping website. When a customer clicks the Add to Cart button:

  • A click event is triggered.
  • The product is added to the cart.
  • The cart item count stored in state increases.
  • React automatically updates the cart icon without refreshing the page.

This smooth user experience is made possible by combining state and event handling.

Summary

State and event handling are two of the most important concepts in React. State stores data that can change, while event handling allows your application to respond to user actions.

Together, they make React applications interactive, dynamic, and user-friendly. Whether you are building a counter, a login form, or an online shopping cart, you will use state and events in almost every React project.

Key Takeaways

  • State stores data that can change over time.
  • React uses the useState Hook to create and manage state.
  • Always update state using its setter function, such as setCount().
  • Event handling allows React to respond to user actions.
  • Common events include onClick, onChange, and onSubmit.
  • State and events work together to create interactive user interfaces.
  • React automatically updates the UI whenever the state changes.
  • Understanding state and event handling is essential for building modern React applications.
Let's learn with DevBrainBox AI