💻Lecture Notes Of Class 5: State in React

Rashmi Mishra
0

💻Lecture Notes Of Class 5

State in React

🎯 Objective:

To understand and manage component data using the useState hook in React.


🧠 What is State in React?

In React, state is a way to store dynamic data in a component. It allows your component to remember information and update the UI when that information changes.

Think of state as a variable that when changed, automatically re-renders the component to reflect the new data.


🛠️ useState Hook

React provides the useState hook to add state to functional components.

✅ Syntax:

const [stateVariable, setStateFunction] = useState(initialValue);

  • stateVariable: the current value of the state.
  • setStateFunction: a function to update the state.
  • initialValue: the starting value of the state.

🧪 Example:

import React, { useState } from 'react';

function MyComponent() {

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

  return (

    <div>

      <p>You clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>

        Click Me

      </button>

    </div>

  );

}

📝 Explanation:

  • When you click the button, setCount(count + 1) updates the value of count.
  • React re-renders the component and shows the updated count.

🔄 Updating State

You must not modify state directly. Always use the setter function.

❌ Wrong:

count = count + 1; // DO NOT do this

✅ Right:

setCount(count + 1);

State updates are asynchronous, meaning React may batch updates to improve performance. So don't expect immediate changes after calling setCount().


️ Activity: Create a Counter with Increment/Decrement Buttons

Let’s build a simple counter application.

📁 Counter.js:

import React, { useState } from 'react'; 

function Counter() {

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

  const increment = () => {

    setCount(count + 1);

  }; 

  const decrement = () => {

    setCount(count - 1);

  }; 

  return (

    <div style={{ textAlign: 'center', marginTop: '50px' }}>

      <h2>Simple Counter</h2>

      <h3>{count}</h3>

      <button onClick={increment}>Increment</button>

      <button onClick={decrement} style={{ marginLeft: '10px' }}>

        Decrement

      </button>

    </div>

  );

} 

export default Counter;

➕ Output:

  • A number is displayed with Increment and Decrement buttons.
  • Clicking Increment increases the number.
  • Clicking Decrement decreases the number.

🏠 Homework:

🔧 Enhance the above counter by:

1. Adding a Reset Button

  • Add a button that sets the counter to zero.

2. Adding a Step Value

  • Allow users to increase/decrease the counter by a step value (e.g., 2 or 5).

💡 Example Ideas for Homework:

const [step, setStep] = useState(2);

const increment = () => setCount(count + step);

const decrement = () => setCount(count - step);

const reset = () => setCount(0);

Encourage students to:

  • Use a form/input to enter custom step values.
  • Style the buttons using CSS.

📌 Summary:

  • React state allows components to hold and change data.
  • The useState() hook adds state to functional components.
  • Never update state directly, use the setter function.
  • Every state update re-renders the component.
  • Built a simple counter as a hands-on activity.

📚 Practice Questions:

1.   What is the purpose of the useState hook?

2.   Why should you avoid updating state directly?

3.   How can you reset the state to its initial value?

4.   What happens when you update state using the setter function?

Solutions:

1. What is the purpose of the useState hook?

The useState hook is used to add state to functional components in React.
Before hooks, only class components could have state. With useState, you can store and manage values that may change over time (like user input, toggle states, counters, etc.).

Syntax:

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

  • count is the current state value.
  • setCount is the function to update the state.
  • 0 is the initial state value.

2. Why should you avoid updating state directly?

You should avoid updating state directly because:

  • It won't trigger a re-render: React only re-renders the component when state is updated using the setter function.
  • Bypasses React’s internal management: Direct changes don’t register in React’s state system.
  • Can cause bugs: It may lead to unexpected behavior, especially in complex UIs.

❌ Incorrect:

count = count + 1; // Direct mutation — don't do this!

✅ Correct:

setCount(count + 1); // Triggers a re-render


3. How can you reset the state to its initial value?

To reset the state, simply call the setter function with the initial value.

Example:

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

// Reset to initial value

setName("Rashmi");

Alternatively, if the initial value is from a variable:

const initialName = "Rashmi";

const [name, setName] = useState(initialName);

// Reset later

setName(initialName);


4. What happens when you update state using the setter function?

When you use the setter function (like setCount):

  • React updates the state value.
  • Then it re-renders the component with the new state.
  • The UI reflects the latest changes based on the updated state.

Example:

setCount(count + 1);

This tells React:

  • "Change the count to count + 1"
  • Then, React re-renders the component so that the UI shows the updated count.

🧠 Behind the scenes, React compares the old and new state, and only updates what has changed (efficient re-rendering).

 

Tags

Post a Comment

0Comments

Post a Comment (0)