Popular Searches
Popular Course Categories
Popular Courses

Introduction to State

Introduction to State

State Management with useState

Introduction to State in React JS

Topic: Introduction to State

Technology: React JS

React JS Training: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. Introduction to State

State is a fundamental concept in React that allows a component to store and manage information that can change over time. State helps React applications respond to user interactions, such as clicking buttons, typing into input fields, selecting options, opening menus, and adding products to a shopping cart.

When state changes, React can render the component again to display the updated information. State makes user interfaces dynamic and interactive.

Example

Consider a counter application. Initially, the counter displays 0. When the user clicks the Increase button, the counter changes to 1, then 2, and continues increasing. The changing counter value is stored in state.

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

Explanation: The count variable stores the current value. The setCount function updates it, and React renders the updated count.


2. What Is State in React?

State is data that a component remembers between renders. It is managed by React and can be updated when an event or application action occurs.

Examples of information that can be stored in state include:

  • A counter value.
  • Text entered into a form field.
  • Whether a menu is open or closed.
  • The currently selected tab.
  • Whether a user has enabled dark mode.
  • The items selected for a shopping cart.
  • Loading, success, and error statuses.

Example

import { useState } from "react";
function Message() {
  const [message, setMessage] = useState("Welcome");
  return (
    <div>
      <h2>{message}</h2>
      <button onClick={() => setMessage("Hello React!")}>
        Change Message
      </button>
    </div>
  );
}
export default Message;

Initially, the heading displays Welcome. When the button is clicked, the state changes and the heading displays Hello React!


3. Why Is State Needed in React?

State is needed when a component must remember changing information and display the latest value. Ordinary local variables do not provide the same behavior because changing a local variable does not automatically tell React to render the component again.

State is useful for:

  • Updating the UI after user interaction.
  • Storing form input values.
  • Showing or hiding elements.
  • Managing counters and scores.
  • Tracking selected products or items.
  • Displaying data loading and error states.
  • Controlling interactive components such as tabs, menus, and accordions.

Example: Regular Variable vs State

Regular variable:

function Counter() {
  let count = 0;
  function increase() {
    count = count + 1;
  }
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increase}>Increase</button>
    </div>
  );
}

This example does not update the displayed count reliably. Changing count does not trigger a React render, and a later render creates the local variable again.

Using state:

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

The state version remembers the count between renders and updates the UI when setCount is called.


4. Introduction to the useState Hook

useState is a built-in React Hook that lets functional components store and update state. A Hook is a special React function that provides access to React features.

To use useState, import it from React.

import { useState } from "react";

Syntax

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

Parts of the syntax:

  • state: The current state value.
  • setState: The function used to request a state update.
  • useState(): The Hook that declares the state variable.
  • initialValue: The value used to initialize the state.

Example

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

Here, name initially contains Rahul. The setName function can be used to update the value when required.


5. How State Works in React

React state works by storing a value, responding to an update request, and rendering the component with the latest state.

  1. Initialize state: Declare a state variable using useState.
  2. Display state: Use the state value in JSX.
  3. Handle an event: The user clicks a button or changes an input.
  4. Update state: Call the state setter function.
  5. Re-render: React renders the component with the updated state.

Example

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

When the button is clicked, increaseCount requests the next count value. React then updates the displayed count during the next render.


6. Different Types of State Values

React state can store different JavaScript data types, depending on what the component needs to remember.

6.1 Number State

Number state is useful for counters, scores, quantities, and ratings.

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

6.2 String State

String state is useful for names, messages, search terms, and text inputs.

const [name, setName] = useState("Guest");

6.3 Boolean State

Boolean state is useful for tracking true-or-false conditions, such as whether a menu is open.

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

6.4 Array State

Array state can store lists of tasks, products, names, or selected items.

const [items, setItems] = useState(["HTML", "CSS"]);

6.5 Object State

Object state can store related information, such as a user's profile or form details.

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

7. Updating State with a Setter Function

The setter returned by useState is used to request a state update. Calling the setter does not change the state variable in the already executing code. The updated value is available when React renders the component again.

Example

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

Clicking Change Name updates the state from Amit to Priya.


8. Updating State Based on the Previous Value

When the next state depends on the previous state, use an updater function. This is especially helpful when multiple updates are queued together.

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 pending previous value and returns the next value. Clicking the button increases the count by three.


9. Managing Multiple State Variables

A component can have more than one state variable. This is useful when the component needs to track separate pieces of information.

Example

import { useState } from "react";
function Profile() {
  const [name, setName] = useState("Neha");
  const [age, setAge] = useState(22);
  return (
    <div>
      <h2>Name: {name}</h2>
      <p>Age: {age}</p>
      <button onClick={() => setName("Riya")}>Change Name</button>
      <button onClick={() => setAge(age + 1)}>Increase Age</button>
    </div>
  );
}
export default Profile;

The name and age variables maintain separate state values. Each setter updates its corresponding state.


10. Updating Object State

Objects can be stored in state, but they should not be mutated directly. Instead, create a new object with the updated property.

Example

import { useState } from "react";
function Profile() {
  const [user, setUser] = useState({
    name: "Aarav",
    city: "Mumbai"
  });
  function changeCity() {
    setUser({
      ...user,
      city: "Pune"
    });
  }
  return (
    <div>
      <p>Name: {user.name}</p>
      <p>City: {user.city}</p>
      <button onClick={changeCity}>Change City</button>
    </div>
  );
}
export default Profile;

The spread syntax copies the existing user properties, and the city property is replaced in the new object.


11. Updating Array State

When updating an array in state, create a new array instead of modifying the existing array directly.

Example: Adding an Item

import { useState } from "react";
function TodoList() {
  const [todos, setTodos] = useState(["Learn HTML", "Learn CSS"]);
  function addTodo() {
    setTodos(previousTodos => [...previousTodos, "Learn React"]);
  }
  return (
    <div>
      <ul>
        {todos.map((todo) => (
          <li key={todo}>{todo}</li>
        ))}
      </ul>
      <button onClick={addTodo}>Add Task</button>
    </div>
  );
}
export default TodoList;

The spread syntax copies the previous array and adds a new item at the end.


12. State and Event Handling

State is often updated in response to events, such as clicks, text input, form submissions, and checkbox changes.

Example: Toggle Visibility

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

The visible state controls whether the message appears. Clicking the button switches the state between true and false.


13. State in Forms

State is commonly used to store form input values. A controlled input uses a state value for its value and an onChange handler to update that state.

Example

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

Every time the user types, onChange updates the name state and React displays the current value.


14. Rules for Using useState

  • Call useState at the top level of a functional component or a custom Hook.
  • Do not call Hooks inside loops, conditions, or nested functions.
  • Use the setter function to request state updates.
  • Do not modify objects or arrays in state directly.
  • Use updater functions when the next value depends on the previous value.
  • Keep unrelated state values separate when that makes the code easier to understand.
  • Avoid storing redundant information that can be calculated from existing state or props.

15. Common Mistakes When Using State

Mistake Problem Correct Approach
Using a regular variable for changing UI data Changing it does not trigger a render Use useState for data the component must remember
Changing state directly Mutating existing objects or arrays can cause bugs Create a new object or array and pass it to the setter
Calling a setter during every render May create an infinite render loop Update state in event handlers or suitable logic
Expecting the current variable to change immediately The current render retains its state snapshot Use the new state value on a later render
Calling useState inside a condition Breaks the Rules of Hooks Call Hooks at the top level
Storing duplicate state Different values can become inconsistent Calculate values from existing state when possible

16. Difference Between Props and State

Feature Props State
Meaning Inputs passed to a component Information remembered by a component
Typical source Parent component Declared and managed by a state owner
Update mechanism Parent supplies new values State setter requests an update
Purpose Configure a component Track information that changes over time
Example const [count, setCount] = useState(0)

17. Practical Project: Counter Application

Objective: Create a counter with Increase, Decrease, and Reset buttons using React state.

App.jsx

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

Project Outcome: The application stores the count in state and updates the displayed value when the user clicks a button.


18. Interview Questions and Answers

Q1. What is state in React?

State is information a component remembers between renders and can update in response to events or other application actions.

Q2. What is the useState Hook?

useState is a built-in React Hook that declares a state variable and returns its current value along with a setter function.

Q3. What does useState return?

It returns an array containing two items: the current state value and a function to request updates.

Q4. Why should we use state instead of regular variables?

State persists between renders and its setter requests a render so the UI can reflect the new value.

Q5. Can a component have multiple state variables?

Yes. A component can declare multiple state variables for different pieces of information.

Q6. Can state contain an object or array?

Yes. State can hold numbers, strings, booleans, arrays, objects, and other JavaScript values.

Q7. Why should state not be mutated directly?

React state should be treated as read-only. Create a new object or array when updating structured state.

Q8. What is a state setter function?

It is the function returned by useState that requests the next state value.

Q9. What happens when state changes?

React schedules a render so the component can display the updated state. React may batch multiple updates.

Q10. What is the difference between props and state?

Props are inputs supplied to a component, while state is information managed by the component or its state owner.


19. Practice Exercises

  1. Create a counter that increases by one when a button is clicked.
  2. Create a button that changes a message from Welcome to Hello React.
  3. Build a show/hide feature using boolean state.
  4. Create a form that stores and displays a user's name.
  5. Build a task list that allows users to add items using array state.
  6. Create a profile component that updates a city stored in object state.
  7. Build a simple like button that toggles between Like and Liked.
  8. Create a counter with Increase, Decrease, and Reset buttons.

20. Best Practices for Managing State

  • Keep state as simple as possible.
  • Use descriptive names for state variables and setter functions.
  • Use state only for information that needs to be remembered between renders.
  • Do not store values that can easily be calculated from existing props or state.
  • Use functional updater syntax when the next state depends on the previous state.
  • Replace objects and arrays instead of mutating them.
  • Group related state values when they are always updated together.
  • Move state to a common parent when multiple components need to share it.

21. Quick Revision Checklist

  • Understand the meaning and purpose of state.
  • Know how to import and use useState.
  • Understand the current state value and setter function.
  • Practice updating number, string, boolean, array, and object state.
  • Know how state updates cause React to render again.
  • Understand the difference between props and state.
  • Know the Rules of Hooks.
  • Avoid direct state mutation.
  • Practice building interactive components.

22. Useful Learning Resources


23. Conclusion

State is one of the core concepts in React JS. It enables components to remember changing information and update the user interface in response to interactions. By learning useState, setter functions, event handling, and safe updates to objects and arrays, developers can create interactive and maintainable React applications.

Learn React JS: Explore JustAcademy React JS Training

Course Demo: Register for a React JS Course Demo

whatsapp