Popular Searches
Popular Course Categories
Popular Courses

Introduction to State

Introduction to State

State Management with useState

Introduction to State in React JS – Complete Detailed Notes

Course: React JS Training

Topic: Introduction to State

Learning Objectives: Understand React state, learn the difference between state and props, use the useState() Hook, update state through events, handle multiple state variables, and build interactive React components.

Official Documentation: React – State: A Component's Memory


1. Introduction to State in React

State is one of the fundamental concepts in React. It allows a component to store information that can change over time and update the user interface when that information changes.

In a React application, users interact with the interface by clicking buttons, typing into input fields, selecting options, opening menus, and submitting forms. These interactions often change what the application should display. React state helps manage these changes.

For example, state can store:

  • The current value of a counter.
  • The text entered into a search box.
  • Whether a menu is open or closed.
  • Whether a user has selected a checkbox.
  • The items added to a shopping cart.
  • The current tab selected on a dashboard.
  • Whether a form has been submitted successfully.
  • The current page or selected image in a gallery.

State is often described as a component's memory because React remembers its state between renders. When the state is updated, React can render the component again to display the latest information.

2. What Is State in React?

State is data managed by a React component that may change during the application's execution. Unlike an ordinary local variable, state is retained by React between renders.

Example of a Counter

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h2>Counter: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}
export default Counter;

Explanation:

  • useState(0) initializes the counter with a value of zero.
  • count represents the current state value.
  • setCount is the function used to request a state update.
  • When the button is clicked, the count is increased by one.
  • React renders the component again so the updated count appears on the screen.

Every time the user clicks the Increase button, the displayed counter changes without manually modifying the DOM.

3. Why Do We Need State?

React components often need to remember information and display different content depending on user interactions. Ordinary JavaScript variables are not sufficient for this purpose because changing a local variable does not automatically tell React to render the component again.

Example Without State

function Counter() {
  let count = 0;
  function increaseCount() {
    count = count + 1;
    console.log(count);
  }
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increaseCount}>Increase</button>
    </div>
  );
}
export default Counter;

Problem: Clicking the button changes the local variable and logs a new value, but React does not automatically re-render the component because the variable changed. The displayed count therefore remains unchanged.

Correct Approach Using State

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  function increaseCount() {
    setCount(count + 1);
  }
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increaseCount}>Increase</button>
    </div>
  );
}
export default Counter;

Using state allows React to remember the current count and schedule a new render when the update is requested.

4. Understanding the useState() Hook

useState() is a built-in React Hook that allows a functional component to store and update state.

To use it, import useState from React.

import { useState } from "react";

The basic syntax is:

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

Here:

  • state is the current state value for the current render.
  • setState is the setter function used to request a new state value.
  • initialValue is the value used when the component's state is initialized.

Example

import { useState } from "react";
function App() {
  const [name, setName] = useState("Rahul");
  return (
    <div>
      <h2>Name: {name}</h2>
      <button onClick={() => setName("Amit")}>
        Change Name
      </button>
    </div>
  );
}
export default App;

Initially, the component displays Rahul. When the button is clicked, the setter requests a new value, Amit, and React renders the updated name.

5. Understanding State Variables and Setter Functions

A state declaration normally contains two values returned by the useState() Hook.

const [age, setAge] = useState(20);

State variable – age

It contains the current age value for the current render. In the initial render, the value is 20.

Setter function – setAge

It requests that React update the state value. For example:

setAge(21);

After React processes the update, the component renders using the new state value.

Important: Calling a setter does not immediately change the state variable in the currently executing function. It requests an update for a subsequent render.

6. How State Updates Work

When state is updated, React follows a rendering process to reflect the latest information in the user interface.

  1. Initial render: React calls the component and displays the initial state.
  2. User interaction: The user clicks a button or changes an input.
  3. State update: The event handler calls the setter function.
  4. Re-render: React calls the component again using the updated state.
  5. UI update: React updates the necessary parts of the displayed interface.

Example

import { useState } from "react";
function ToggleMessage() {
  const [visible, setVisible] = useState(false);
  return (
    <div>
      <button onClick={() => setVisible(!visible)}>
        Toggle Message
      </button>
      {visible && <p>Welcome to React JS!</p>}
    </div>
  );
}
export default ToggleMessage;

Initially, the message is hidden because visible is false. Clicking the button changes the state, allowing React to display or hide the message.

7. State vs. Props in React

State and props both influence what a component displays, but they serve different purposes.

Feature State Props
Meaning Data managed by a component Data passed to a component
Primary purpose Store information that changes over time Configure a component with external data
Updated by The component's setter or state-management logic The parent changes the values it passes
Typical examples Counter value, input text, menu visibility Username, product title, course fee
Mutability Update using the appropriate setter or reducer Treat props as read-only
Re-rendering State updates can trigger a re-render New props can trigger a re-render

Example of Props

function Welcome({ name }) {
  return <h2>Welcome, {name}!</h2>;
}
function App() {
  return <Welcome name="Priya" />;
}
export default App;

The parent supplies the name through props.

Example of State

import { useState } from "react";
function Welcome() {
  const [name, setName] = useState("Priya");
  return (
    <div>
      <h2>Welcome, {name}!</h2>
      <button onClick={() => setName("Neha")}>
        Change Name
      </button>
    </div>
  );
}
export default Welcome;

In this example, the component manages the name using its own state.

8. Types of Values That Can Be Stored in State

React state can hold different types of JavaScript values. The appropriate type depends on the information a component needs to remember.

8.1 Number State

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

Used for counters, quantities, scores, pagination indexes, and other numeric values.

8.2 String State

const [username, setUsername] = useState("");

Used for names, search terms, messages, and form input text.

8.3 Boolean State

const [isOpen, setIsOpen] = useState(false);

Used for visibility, checkbox status, expanded panels, and enabled or disabled features.

8.4 Array State

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

Used for task lists, shopping-cart items, search results, and collections of records.

8.5 Object State

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

Used for related information such as user profiles, form data, settings, and product details.

9. Managing Multiple State Variables

A component can contain multiple state variables. This is useful when the component needs to remember different pieces of information.

import { useState } from "react";
function UserProfile() {
  const [name, setName] = useState("Rahul");
  const [age, setAge] = useState(22);
  const [isStudent, setIsStudent] = useState(true);
  return (
    <div>
      <h2>Name: {name}</h2>
      <p>Age: {age}</p>
      <p>Student: {isStudent ? "Yes" : "No"}</p>
      <button onClick={() => setName("Amit")}>Change Name</button>
      <button onClick={() => setAge(age + 1)}>Increase Age</button>
      <button onClick={() => setIsStudent(!isStudent)}>Toggle Student</button>
    </div>
  );
}
export default UserProfile;

This component manages three independent pieces of state: a name, an age, and a student status. Each setter updates its corresponding state variable.

10. Updating State Using Event Handlers

Event handlers are functions that run in response to user actions. In React, event handlers commonly update state to change the interface.

Example: Increase and Decrease Counter

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  function increase() {
    setCount(count + 1);
  }
  function decrease() {
    setCount(count - 1);
  }
  function reset() {
    setCount(0);
  }
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increase}>Increase</button>
      <button onClick={decrease}>Decrease</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}
export default Counter;

Explanation:

  • The Increase button adds one to the current count.
  • The Decrease button subtracts one.
  • The Reset button sets the count to zero.
  • Each state update causes React to render the new count.

11. Updating State Based on the Previous State

When a new state value depends on the previous value, using a functional updater is a reliable approach. React supplies the latest queued state value to the updater function.

Example

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  function increaseThreeTimes() {
    setCount(previousCount => previousCount + 1);
    setCount(previousCount => previousCount + 1);
    setCount(previousCount => previousCount + 1);
  }
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increaseThreeTimes}>Increase by 3</button>
    </div>
  );
}
export default Counter;

Each updater receives the result of the previous queued update. Therefore, clicking the button increases the count by three.

Important: When an update depends on the previous state, prefer a functional update such as setCount(previousCount => previousCount + 1). This avoids relying on a potentially outdated state snapshot.

12. State and Conditional Rendering

Conditional rendering means displaying different content depending on a condition. State is frequently used to control these conditions.

Example: Show and Hide Message

import { useState } from "react";
function Message() {
  const [showMessage, setShowMessage] = useState(false);
  return (
    <div>
      <button onClick={() => setShowMessage(!showMessage)}>
        {showMessage ? "Hide Message" : "Show Message"}
      </button>
      {showMessage && <p>State controls this message.</p>}
    </div>
  );
}
export default Message;

When showMessage is true, the paragraph appears. When it is false, the paragraph is not rendered.

13. Handling Input Fields With State

State can store the current value of an input field. When a user types, the onChange event handler updates state.

Example: Name Input

import { useState } from "react";
function NameForm() {
  const [name, setName] = useState("");
  return (
    <div>
      <label htmlFor="name">Enter your name:</label>
      <input
        id="name"
        type="text"
        value={name}
        onChange={event => setName(event.target.value)}
      />
      <p>Your name is: {name}</p>
    </div>
  );
}
export default NameForm;

Explanation:

  • useState("") initializes the name as an empty string.
  • value={name} connects the input value to state.
  • onChange updates the state as the user types.
  • The paragraph displays the current value of the name.

This pattern is called a controlled input because React state controls the displayed input value.

14. Updating Object State

React state can contain objects, but you should not directly mutate an object stored in state. Instead, create a new object and pass it to the setter.

Incorrect Approach

user.name = "Amit";

Directly modifying an existing state object is not the recommended way to update React state.

Correct Approach

import { useState } from "react";
function UserProfile() {
  const [user, setUser] = useState({
    name: "Rahul",
    age: 22
  });
  function changeName() {
    setUser({
      ...user,
      name: "Amit"
    });
  }
  return (
    <div>
      <h2>{user.name}</h2>
      <p>Age: {user.age}</p>
      <button onClick={changeName}>Change Name</button>
    </div>
  );
}
export default UserProfile;

The spread operator copies the existing properties into a new object, and the new name replaces the old value. The age is preserved.

15. Updating Array State

Arrays stored in state should also be updated by creating a new array rather than mutating the existing array.

Example: Add Items to a List

import { useState } from "react";
function ShoppingList() {
  const [items, setItems] = useState(["Milk", "Bread"]);
  function addItem() {
    setItems(previousItems => [...previousItems, "Eggs"]);
  }
  return (
    <div>
      <h2>Shopping List</h2>
      <ul>
        {items.map((item, index) => (
          <li key={`${item}-${index}`}>{item}</li>
        ))}
      </ul>
      <button onClick={addItem}>Add Eggs</button>
    </div>
  );
}
export default ShoppingList;

The spread operator creates a new array containing the previous items and the new item. For a production list where entries can be duplicated or reordered, use stable unique IDs as keys.

16. State Is Local to a Component

State belongs to a particular component instance. If the same component is rendered twice, each instance normally has its own independent state.

Example

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}
function App() {
  return (
    <div>
      <Counter />
      <Counter />
    </div>
  );
}
export default App;

The two counters maintain separate values. Clicking the first counter does not change the second counter because each component instance owns its own state.

17. Rules for Using the useState() Hook

React Hooks follow specific rules that help React associate state with the correct component.

  • Call useState() at the top level of a function component or a custom Hook.
  • Do not call Hooks inside loops, conditions, or nested functions.
  • Use the setter function to request state changes.
  • Do not mutate objects or arrays in state directly.
  • Remember that state updates may be batched by React.
  • Do not expect the state variable in the current render to change immediately after calling its setter.
  • Use functional updates when the next value depends on the previous value.

Incorrect Example

function Example({ enabled }) {
  if (enabled) {
    const [count, setCount] = useState(0);
  }
  return <div>Example</div>;
}

This violates the Rules of Hooks because the Hook is called conditionally.

Correct Example

function Example({ enabled }) {
  const [count, setCount] = useState(0);
  return (
    <div>
      {enabled && <p>Count: {count}</p>}
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

The Hook is called at the top level on every render, while the displayed paragraph is conditional.

18. Common Mistakes When Working With State

Mistake 1: Updating a Normal Variable Instead of State

Changing a local variable does not automatically trigger a React re-render. Use state when the UI must respond to changing data.

Mistake 2: Calling the Setter but Expecting the Current Variable to Change Immediately

function handleClick() {
  setCount(count + 1);
  console.log(count);
}

The log shows the state value from the current render, not necessarily the newly requested value. React processes the update and supplies the updated value on a subsequent render.

Mistake 3: Mutating State Directly

Avoid changing state objects and arrays in place. Create a new object or array and pass it to the setter.

Mistake 4: Ignoring Previous State

When several updates depend on the previous value, use a functional updater to ensure each update is calculated from the latest queued state.

Mistake 5: Calling Hooks Conditionally

Call Hooks at the top level of components or custom Hooks, not inside conditions, loops, or event handlers.

Mistake 6: Storing Unnecessary Duplicate Data

Avoid storing values that can be calculated from existing props or state when they do not need independent management. Duplicated state can become inconsistent.

19. Practical Project: Interactive React Profile

Build a simple profile component that demonstrates string, number, and boolean state in one application.

App.jsx

import { useState } from "react";
function App() {
  const [name, setName] = useState("Rahul");
  const [age, setAge] = useState(22);
  const [isAvailable, setIsAvailable] = useState(true);
  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Status: {isAvailable ? "Available" : "Unavailable"}</p>
      <button onClick={() => setName("Amit")}>Change Name</button>
      <button onClick={() => setAge(previousAge => previousAge + 1)}>Increase Age</button>
      <button onClick={() => setIsAvailable(previous => !previous)}>Toggle Status</button>
    </div>
  );
}
export default App;

Project features:

  • Displays a user's name, age, and availability status.
  • Changes the name when the user clicks the Change Name button.
  • Increases the age using a functional state update.
  • Toggles availability between Available and Unavailable.
  • Demonstrates how state updates cause the UI to change.

20. Practical Exercises

Exercise 1: Counter Application

Create a counter with Increase, Decrease, and Reset buttons. Store the counter value in state.

Exercise 2: Theme Toggle

Create a button that switches between light and dark themes using a boolean state variable.

Exercise 3: Name Input

Create an input field that stores the entered name in state and displays it below the input.

Exercise 4: Student Profile

Create a profile component that stores a student's name, age, and course in state. Add buttons to update the information.

Exercise 5: Shopping List

Create a list that allows users to add new items. Store the list in array state and update it without mutating the existing array.

Exercise 6: Show and Hide Password

Create a password input with a button that toggles its input type between password and text using state.

21. Interview Questions and Answers

Q1. What is state in React?

State is component-managed data that React remembers between renders. Updating it can cause the component to render again with new values.

Q2. Why is state important in React?

State allows interfaces to respond to user actions, such as clicks, typing, selections, and form submissions.

Q3. What is the useState() Hook?

useState() is a built-in React Hook that declares a state variable and returns its setter function.

Q4. What does useState() return?

It returns an array containing the current state value and a setter function.

Q5. What is the difference between state and props?

State is managed by a component, while props are values passed to a component, usually by its parent.

Q6. Does updating state trigger a re-render?

A state update can trigger React to render the component again. React may skip rendering work when the new value is identical to the current value according to its state comparison.

Q7. Can state store objects and arrays?

Yes. State can store numbers, strings, booleans, objects, arrays, and other JavaScript values. Objects and arrays should be updated immutably.

Q8. Why should we not mutate state directly?

Direct mutation can cause React to miss the intended change and makes updates harder to reason about. Create a new value and pass it to the setter instead.

Q9. What is a functional state update?

It passes a function to the setter, such as setCount(previous => previous + 1), so the next value is calculated from the previous state.

Q10. Can a component have multiple state variables?

Yes. A component can call useState() multiple times to manage separate pieces of state.

Q11. Is state shared automatically between two component instances?

No. Each component instance has its own state unless shared state is managed in a common parent or through another appropriate state-management approach.

Q12. Can useState() be called inside an if statement?

No. Hooks must be called at the top level of a component or custom Hook, not conditionally or inside loops.

22. Quick Revision Checklist

  • Understand the meaning and purpose of React state.
  • Understand why ordinary local variables are not sufficient for interactive UI updates.
  • Know how to import and use the useState() Hook.
  • Understand the state variable and setter function.
  • Know how state updates trigger rendering.
  • Understand the difference between props and state.
  • Practice number, string, boolean, object, and array state.
  • Use event handlers to update state.
  • Use functional updates when the next value depends on the previous value.
  • Update objects and arrays without directly mutating them.
  • Follow the Rules of Hooks.
  • Complete the practical exercises and interview questions.

23. Conclusion

State is a fundamental part of React because it allows components to remember changing information and display an updated user interface. The useState() Hook provides a straightforward way to declare state variables and update them in response to user interactions.

By understanding state variables, setter functions, re-rendering, functional updates, controlled inputs, object and array updates, and the Rules of Hooks, developers can build interactive and maintainable React applications.


Learn React JS With JustAcademy

Explore the React JS training course to strengthen your understanding of JSX, components, props, state, Hooks, routing, and practical application development.

JustAcademy React JS Training Course

Interested in learning more about the course? Register for a demo session using the link below.

Register for React JS Course Demo

Previous Next
whatsapp