#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
State and Event Binding

Working with State

State is data that a React component remembers between renders and that can change while the app runs, such as a counter, the text in a search box or whether a menu is open. When state changes, React re-renders the component so the screen matches the new data. In function components you add state with the useState hook.

Why a normal variable is not enough

A plain let count = 0 inside a component has two problems. First, the component function runs again on every render, so the variable is reset to 0 each time. Second, changing it does not tell React to re-render, so the screen does not update. useState solves both: React stores the value between renders, and calling its setter schedules a new render.

Using useState

import { useState } from 'react';

export default function Feedback() {
  const [rating, setRating] = useState(0);
  const [comment, setComment] = useState('');
  const [form, setForm] = useState({ name: '', email: '' });

  function addThree() {
    // Wrong: all three read the same old value, so this adds 1
    // setRating(rating + 1); setRating(rating + 1); setRating(rating + 1);

    // Right: the updater function receives the latest value
    setRating((r) => r + 1);
    setRating((r) => r + 1);
    setRating((r) => r + 1);
  }

  function updateField(event) {
    const { name, value } = event.target;
    setForm((prev) => ({ ...prev, [name]: value }));   // copy, then change
  }

  return (
    <section>
      <p>Rating: {rating}</p>
      <button onClick={() => setRating(rating + 1)}>+1</button>
      <button onClick={addThree}>+3</button>

      <textarea value={comment} onChange={(e) => setComment(e.target.value)} />
      <p>{comment.length} characters</p>

      <input name="name" value={form.name} onChange={updateField} />
      <input name="email" value={form.email} onChange={updateField} />
    </section>
  );
}

useState(0) returns a pair: the current value and a function to update it. Array destructuring lets you name them anything, though the value and setValue pattern is standard.

State updates are not instant

Calling a setter does not change the variable straight away. It asks React to render again with the new value. Inside the same event handler, rating still holds the old number, and logging it right after setRating prints the previous value. React also batches several updates from one event into a single re-render. When the new value depends on the old one, pass a function to the setter, as addThree does, so each update builds on the latest result.

Treat objects and arrays as read-only

This is the pitfall that causes the most confusion. Writing form.name = 'Asha'; setForm(form); changes the existing object and passes the same reference back. React compares the old and new values, sees the same object, and may skip the re-render entirely. Always create a new object or array:

  • Objects: setForm({ ...form, name: 'Asha' })
  • Add to an array: setItems([...items, newItem])
  • Remove: setItems(items.filter((i) => i.id !== id))
  • Change one item: setItems(items.map((i) => (i.id === id ? { ...i, done: true } : i)))

Deciding what belongs in state

Store only what cannot be calculated. In the example, the character count comes from comment.length, so it is not a separate state value. Keeping duplicated data in state means remembering to update both copies, and they will eventually disagree. Also keep state in the lowest component that needs it; if two siblings need the same value, move it up to their parent and pass it down as props.

Each component instance has its own state. Rendering <Feedback /> twice gives two independent ratings.

Core rules for state

Use useState for values that change and affect the display, update them only through the setter, use the updater form when the next value depends on the previous one, never modify objects or arrays in place, and avoid storing anything you can compute from existing state or props.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course