0% found this document useful (0 votes)
7 views9 pages

React useState and Event Handling Guide

This document outlines a Week 4 lesson plan focused on managing state in React using the useState hook and event handling. It covers the basics of state, practical use cases, and includes hands-on coding activities such as building a counter and a to-do list. The session aims to enhance students' skills in creating interactive web applications that respond to user input.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

React useState and Event Handling Guide

This document outlines a Week 4 lesson plan focused on managing state in React using the useState hook and event handling. It covers the basics of state, practical use cases, and includes hands-on coding activities such as building a counter and a to-do list. The session aims to enhance students' skills in creating interactive web applications that respond to user input.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Week 4 - Managing State in React with useState and Introduction to Event

Handling

Instructor Script:

Introduction: “Hello, good evening, and welcome! Today, we’ll dive into state management in
React using the useState hook, covering how it works, how to set it up in components, and
ways to handle user events and updates. Our goal is to strengthen your foundation in creating
interactive elements and managing component states effectively. By the end of today’s session,
you’ll be able to build components that dynamically change based on user input, a skill essential
for crafting responsive web applications. Let’s briefly review what we covered last week on
React component structure and props before jumping into useState.”

Recap of Week 3 (15 minutes)

Instructor Script: "Before we dive deeper into React, let's revisit some of the basics we learned
last week about components, JSX, and props. These concepts are essential as they form the
foundation for today’s class on state management and event handling.

"To briefly summarize:

1. Components are reusable pieces of UI that make our application modular and
manageable.
2. JSX allows us to write JavaScript code that resembles HTML, letting us create UI
elements with embedded JavaScript expressions.
3. Props help us pass data from a parent component to a child component, making our
components flexible and reusable."

Review Code Example:

javascript
Copy code
// A simple Greeting component that accepts props
function Greeting(props) {
return <h1>Hello, {[Link]}!</h1>;
}

// Parent component using the Greeting component


function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}

Explanation: "This example shows how props are used to pass values like 'Alice' and 'Bob' into
the Greeting component, creating customized greetings. Each <Greeting /> component
receives a different name prop, which updates the message displayed to the user. Props are
read-only and are usually determined by the parent component."

Prompt for Questions: "Any questions about last week’s concepts before we move on?"

Introduction to State in React (20 minutes)

Instructor Script: "Today, we’re focusing on a new concept in React called state. State is
different from props because it allows each component to keep track of its own data. While
props are data sent from parent components, state is managed internally within a component
and can be updated based on user actions.

"When we say a component 'has state,' it means the component can track information that
changes over time, such as user input, counts, toggle switches, or form values. Every time the
state changes, React re-renders the component so the UI stays updated."

Use Case Examples of State:

1. Tracking the number of times a button is clicked.


2. Showing or hiding content based on a toggle.
3. Managing form inputs for a form submission.

Deep Dive into useState (35 minutes)

Instructor Script: "To use state in a functional component, React provides a special function
called useState, which is a hook. useState allows us to declare a state variable and an
update function to change its value. Here’s how it works:

javascript
Copy code
const [stateVariable, setStateVariable] = useState(initialValue);
"useState returns two things:

1. A state variable, which holds the current value of the state.


2. An update function, which is used to change the state value."

Activity Example: Building a Counter

1. Code Setup: Let’s build a basic counter component that keeps track of how many times
a button is clicked.

Example Code:

javascript
Copy code
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // Initializing state

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}

2. Explanation: "In this code:


○ count is our state variable, initialized to 0.
○ setCount is our function to update count.
○ The button’s onClick event calls setCount(count + 1), increasing count
by 1.

"Each time we click the button, React automatically re-renders the component, updating count
in the <p> tag. This showcases how state allows us to manage and update data in response to
user actions."

Hands-On Interaction: "Try changing the initial value in useState(0) to a different number
like 5. This shows how the initial state value influences the displayed count."
Practical Use Cases of State and useState (30 minutes)

Instructor Script: "Let’s dive deeper into the practical uses of state. As you build more
interactive components, you’ll find that state is useful for more than just counting clicks. Let’s
look at three practical examples:

1. Tracking Toggle States – Great for showing/hiding elements.


2. Form Inputs – Useful for capturing user input in real-time.
3. Dynamic Content – Managing which content displays based on state changes."

Extended Example 1: Toggle State Component

Example Code:

javascript
Copy code
import React, { useState } from 'react';

function ToggleMessage() {
const [isVisible, setIsVisible] = useState(true);

return (
<div>
<p>{isVisible ? "Hello, World!" : "Goodbye, World!"}</p>
<button onClick={() => setIsVisible(!isVisible)}>Toggle
Message</button>
</div>
);
}

Explanation: "In this code:

● isVisible is a boolean state initialized to true.


● The button toggles isVisible between true and false.
● If isVisible is true, 'Hello, World!' is displayed; otherwise, 'Goodbye, World!'
appears.

"This component is useful for toggling content on and off, such as showing a login form when a
user clicks ‘Login’."
Interactive Prompt: "Try modifying this example by changing the messages displayed in each
state. For example, instead of 'Hello, World!' and 'Goodbye, World!', try 'Show' and 'Hide' or
'Expand' and 'Collapse'."

Event Handling with State (30 minutes)

Instructor Script: "Now that we understand how useState can help us manage dynamic data,
let’s learn how to handle events in React. Event handling lets us respond to user actions like
clicks, typing, or form submissions, which then trigger changes in state.

"In React, event handling is similar to standard JavaScript, but with some differences:

1. React events are written in camelCase, so onclick becomes onClick.


2. Instead of setting events directly in HTML, React lets us pass functions directly as event
handlers."

Example: Event Handling with a Simple Form

Example Code:

javascript
Copy code
import React, { useState } from 'react';

function GreetingForm() {
const [name, setName] = useState("");

const handleChange = (event) => {


setName([Link]); // Updating state with input value
};

return (
<div>
<input type="text" value={name} onChange={handleChange}
placeholder="Enter your name" />
<p>Hello, {name ? name : "Stranger"}!</p>
</div>
);
}
Explanation: "In this code:

● name is a state variable storing the user’s input.


● handleChange is an event handler that updates name each time the user types.
● As the user types, name updates, and the message greets the user by name in
real-time.

"This example shows how we can capture input and update state simultaneously, allowing us to
provide instant feedback to the user."

Activity Suggestion: "Try changing the placeholder text in the <input> to another prompt like
‘Enter your username.’ This is a simple but effective way to create real-time feedback in your
UI."

Hands-On Coding Activity: Creating a "To-Do" List with State (40 minutes)

Activity Goal: Build a simple to-do list that lets users add items to a list dynamically.

1. Instructor Script: "Now we’ll build a to-do list component. This will give us practice
working with state and event handlers to capture and display dynamic user input."

Example Code:

javascript
Copy code
import React, { useState } from 'react';

function TodoList() {
const [task, setTask] = useState("");
const [tasks, setTasks] = useState([]);

const handleInputChange = (event) => {


setTask([Link]);
};

const handleAddTask = () => {


if ([Link]() !== "") {
setTasks([...tasks, task]);
setTask("");
}
};
return (
<div>
<input
type="text"
value={task}
onChange={handleInputChange}
placeholder="Enter a task"
/>
<button onClick={handleAddTask}>Add Task</button>

<ul>
{[Link]((task, index) => (
<li key={index}>{task}</li>
))}
</ul>
</div>
);
}

2. Explanation:
○ task holds the current input, and tasks is an array holding all the added tasks.
○ handleInputChange updates task as the user types.
○ handleAddTask adds the current task to tasks when the button is clicked and
resets the task input.
○ Finally, the handleAddTask function pushes the current task into the tasks
array, which holds all the added tasks, and then resets task to an empty string.
This enables a fresh start for each new input while storing the existing tasks in
the tasks array for display or further manipulation.
3. useState Array Handling Example:
○ In this example, users can add multiple items to a list, demonstrating array
handling in useState and practical user input tracking.

Code:

javascript
Copy code
import React, { useState } from 'react';
function ItemList() {
const [item, setItem] = useState("");
const [items, setItems] = useState([]);

const addItem = () => {


if ([Link]()) {
setItems([...items, item]);
setItem("");
}
};

return (
<div>
<input type="text" value={item} onChange={(e) =>
setItem([Link])} placeholder="Add item" />
<button onClick={addItem}>Add</button>
<ul>
{[Link]((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}

Explanation:

● item is updated with setItem to reflect input changes.


● addItem pushes each new item to the items array.
● We use .map() to render each item in the array as a list element.

Conclusion (10 minutes)

Instructor Script: “Today, we went deep into the useState hook, learning to create and
manage dynamic states within our components. With this knowledge, you can now create
interfaces that not only display information but also respond to user input and actions, a key
step in mastering React’s core functionalities.”
Preview for Week 5:
“Next week, we’ll expand our toolkit with the useEffect hook, a powerful feature for handling
side effects in functional components. You’ll learn to manage API calls, set up timers, and
respond to component lifecycle events, allowing for more advanced data management and
interactions in your applications. This will be crucial as we move towards building more complex
and data-driven components.”

You might also like