2.4K Views

REACT106 - State & useState Hook

Learn what state is in React, why normal variables are not enough, and how to manage dynamic data using the useState hook.

State is the heart of every interactive React application.
In this lesson, you will learn what state is, why it exists, and how to manage it using the useState hook.

What Is State?

State represents data that can change over time inside a component.
When state changes, React automatically re-renders the component to reflect the new data.

Examples of state data:

  • Counter values
  • Form inputs
  • Toggle flags
  • API responses

Why Not Use Normal Variables?

Normal JavaScript variables do not trigger re-renders when they change.

Example problem:

let count = 0;
 
function Counter() {
  function increment() {
    count ++;
  }
 
  return <button onClick={increment}>{count}</button>;
}

Even though count changes, React does not update the UI.
This is why state is required.


Introducing useState

useState is a React Hook that lets you add state to functional components.

Basic syntax:

const [state, setState] = useState(initialValue);

Example:

import { useState } from "react";
 
function Counter() {
  const [count, setCount] = useState(0);
 
  return <button>{count}</button>;
}

Updating State

State should always be updated using the setter function.

setCount(count + 1);

React schedules a re-render whenever state updates.


Handling Events with State

function Counter() {
  const [count, setCount] = useState(0);
 
  function increment() {
    setCount(count + 1);
  }
 
  return <button onClick={increment}>{count}</button>;
}

Now the UI updates correctly on every click.


Updating State Based on Previous State

When state depends on its previous value, use a callback.

setCount(prev => prev + 1);

This prevents bugs caused by stale state values.


Multiple State Values

You can use useState multiple times in a component.

const [name, setName] = useState("");
const [age, setAge] = useState(0);

Each state value is independent.


State with Objects

State can store objects, but updates must be immutable.

const [user, setUser] = useState({
  name: "Emre",
  age: 30
});

Updating safely:

setUser({
  ...user,
  age: 31
});

Never mutate state directly.


State with Arrays

const [items, setItems] = useState([]);

Adding items:

setItems([...items, "new item"]);

Common State Mistakes

  • Modifying state directly
  • Forgetting to use setter functions
  • Using state when props are enough
  • Overusing state

Understanding state scope is key to clean React code.


Summary

In this lesson, you learned:

  • What state is and why it exists
  • Why normal variables fail in React
  • How to use the useState hook
  • Updating state correctly
  • Handling events with state
  • Managing objects and arrays in state

In the next lesson, we will explore handling events in React and connect state with user interactions.