chore(curriculum): adding transcript and video ids to React state and events lecture block (#59473)

Co-authored-by: Dario-DC <105294544+Dario-DC@users.noreply.github.com>
Co-authored-by: Tom <20648924+moT01@users.noreply.github.com>
Co-authored-by: Kristofer Koishigawa <2051070+scissorsneedfoodtoo@users.noreply.github.com>
This commit is contained in:
Jessica Wilkins
2025-04-11 00:42:06 -07:00
committed by GitHub
parent 7329ddbe2f
commit f07aa3016a
6 changed files with 611 additions and 42 deletions

View File

@@ -8,7 +8,7 @@
"challengeOrder": [
{
"id": "67d1a3fea729e274dc33d04d",
"title": "How Do Events Work in React"
"title": "How Do Events Work in React?"
},
{
"id": "67d1eaf77f510e15dfed7c14",

View File

@@ -1,14 +1,96 @@
---
id: 67d1a3fea729e274dc33d04d
title: How Do Events Work in React
title: How Do Events Work in React?
challengeType: 11
videoId: nVAaxZ34khk
videoId: M8kyPCAb94w
dashedName: how-do-events-work-in-react
---
# --description--
Watch the video lecture and answer the questions below.
Watch the video or read the transcript and answer the questions below.
# --transcript--
How do events work in React?
Event handling is an essential part of every interactive website.
React provides a powerful and consistent way to handle events through its Synthetic Event System, which is a wrapper around native events like `click`, `keydown`, and `submit` you learned about in earlier lectures.
This cross-browser wrapper ensures that events work the same across all browsers so there are no inconsistencies.
Let's see how events work in React so you can start using them in your projects.
In React, event handlers work in a similar way to native browser events, but with a few tweaks.
Instead of using lowercase event attribute names like `onclick` and `onsubmit`, React uses camelCase, like `onClick` and `onSubmit`.
In addition, instead of using strings to specify the kind of event, React expects a function for the event handler.
The event handler function is passed to the element as a prop, and the event type like `onClick` or `onSubmit` is used as an attribute in JSX.
Here is a reminder of how to work with a click event in regular HTML:
```html
<button onclick="alert('Button clicked!')">Click Me</button>
```
And here is how you do the same in React:
```jsx
function handleClick() {
console.log("Button clicked!");
}
<button onClick={handleClick}>Click Me</button>;
```
In this example, `handleClick` logs a message to the console when the user clicks the button.
Note that you don't need parentheses after `handleClick` in the `onClick` attribute, as you're passing a reference to the function, not calling it.
In React, event handler functions usually start with the prefix `handle` to indicate they are responsible for handling events, like `handleClick` or `handleSubmit`.
When a user action triggers an event, React passes a Synthetic Event object to your handler. This object behaves much like the native event object in vanilla JavaScript, providing properties like `type`, `target`, and `currentTarget`.
You can pass `event` as a parameter to the handler function and log it to the console to take a look at its structure:
```js
function handleClick(event) {
console.log(event);
}
```
To prevent default behaviors like browser refresh during an `onSubmit` event, for example, you can call the `preventDefault()` method:
```jsx
function handleSubmit(event) {
event.preventDefault();
console.log("Form submitted!");
}
<form onSubmit={handleSubmit}>
<input type="text" />
<button>Submit</button>
</form>;
```
You can also stop an event from bubbling up to parent elements by calling `event.stopPropagation()`.
Sometimes, while handling special cases like delete and edit features, you might want to pass extra data to an event handler. You can do this by wrapping the handler in an inline arrow function:
```jsx
function handleDelete(id) {
console.log("Deleting item:", id);
}
<button onClick={() => handleDelete(1)}>Delete Item</button>;
```
It's fine to use inline event handlers in React because React efficiently manages re-renders and avoids performance issues.
In vanilla JavaScript, inline event handlers can lead to performance issues by creating new functions on every render, as there is no virtual DOM to optimize the process.
# --questions--
@@ -22,7 +104,7 @@ By only using native browser events.
### --feedback--
Think about React's approach to standardizing event handling.
Review the beginning of the video where the answer was discussed.
---
@@ -30,7 +112,7 @@ By creating custom events for each browser.
### --feedback--
Think about React's approach to standardizing event handling.
Review the beginning of the video where the answer was discussed.
---
@@ -42,7 +124,7 @@ By directly modifying the DOM for each event.
### --feedback--
Think about React's approach to standardizing event handling.
Review the beginning of the video where the answer was discussed.
## --video-solution--
@@ -86,7 +168,7 @@ Think about the method that stops the default browser actions.
## --text--
How does React name event attributes differently from standard HTML?
How does React differ from standard HTML in naming event attributes?
## --answers--

View File

@@ -2,13 +2,130 @@
id: 67d1eaf77f510e15dfed7c14
title: What is State, and How Does the useState Hook Work?
challengeType: 11
videoId: nVAaxZ34khk
videoId: d4guPmZvH_M
dashedName: what-is-state-and-how-does-the-usestate-hook-work
---
# --description--
Watch the lecture video and answer the questions below.
Watch the video or read the transcript and answer the questions below.
# --transcript--
What is state, and how does the `useState` hook work?
State is one of the most important fundamentals of React and other frontend frameworks. It's like the brain of a component, meaning it holds information that can change over time and controls how the components behave and look.
Let's look into what state is and how the `useState` hook lets you work with it.
State represents the dynamic data in your React component, like the value from a user input, data fetched from an API, or an item in a to-do list.
Whenever the state changes, React re-renders the component without reloading the page to reflect those changes in the user interface. This reactivity makes your app interactive.
The `useState` hook is a function that lets you declare state variables in functional components. 
Before hooks, you could only use state in class components. But with the introduction of hooks since React 16.8, you can use state in functional components by using the `useState` hook.
To use the `useState` hook, you need to import it from React:
```js
import { useState } from "react";
```
You can also import React itself and get access to the `useState` hook as a property:
```js
import React from "react";
```
Here's how you can declare a state variable when you import `useState`:
```js
const [stateVariable, setStateFunction] = useState(initialValue);
```
And here's how you can declare a state variable when you import React:
```js
const [stateVariable, setStateFunction] = React.useState(initialValue);
```
In the state variable you have the following:
- `stateVariable` holds the current state value
- `setStateFunction` (the setter function) updates the state variable
- `initialValue` sets the initial state
Note that the state in a React component is private, and is isolated to each component instance. This means that, if you render the same component twice, the state component of one does not affect the other. This also means that, if you'd like to share state between components, then you'd need to lift the state up to a common parent and pass it down as props.
Another thing is that hooks must be called at the top level of a component, just before the `return` keyword, to keep the state and effects consistent across renders. This means you can't use state inside loops, conditions, or nested functions.
Here's an example of managing state with the `useState` hook in a `Counter` component:
```jsx
// Importing the useState hook
import { useState } from "react";
function Counter() {
const initialValue = 0;
// The state variable and setter function
const [count, setCount] = useState(initialValue);
return (
<div>
{/* Display current state value */}
<h2>{count}</h2>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
```
In the code above, we have the `useState` hook imported from React. In the `Counter` component, the `count` represents the current state while `setCount` is the set function responsible for updating state. The current state value is `0`. The `return` statement contains the count and two buttons to decrement and increment the count by `1`.
You can manage multiple pieces of state by calling the `useState` hook multiple times. This is especially important when you have unrelated state variables:
```js
function UserProfile() {
const [isOnline, setIsOnline] = useState(false);
const [notifications, setNotifications] = useState(0);
// The rest of the component logic
}
```
You can also call the `useState` hook multiple times when managing multiple states that update separately, like form fields:
```js
function SignUpForm() {
const [name, setName] = useState("");
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
// The rest of the component logic
}
```
But in this case, it's best to combine the states since they're all part of the same form:
```js
function SignUpForm() {
const [formData, setFormData] = useState({
name: "",
username: "",
email: "",
});
// The rest of the component logic
}
```
That's what state is and how you can use the `useState` hook.
# --questions--
@@ -22,7 +139,7 @@ React 15.6
### --feedback--
This version introduced useState and other hooks.
Review the beginning of the video where the answer was discussed.
---
@@ -34,7 +151,7 @@ React 17.0
### --feedback--
This version introduced useState and other hooks.
Review the beginning of the video where the answer was discussed.
---
@@ -42,7 +159,7 @@ React 18.2
### --feedback--
This version introduced useState and other hooks.
Review the beginning of the video where the answer was discussed.
## --video-solution--
@@ -86,35 +203,59 @@ Think about data that makes the UI interactive and updates without page reloads.
## --text--
How can you manage multiple pieces of state in a React functional component?
Which of the following is the correct way to work with the `useState` hook?
## --answers--
By combining all state values into one `useState` call.
```js
const [formData, setFormData] = useState(<
name: "",
username: "",
email: "",
>);
```
### --feedback--
Think about a way to track different pieces of state independently.
Review the end of the video where the answer was discussed.
---
By using only class components.
```js
const ref = useState({
name: "",
username: "",
email: "",
});
```
### --feedback--
Think about a way to track different pieces of state independently.
Review the end of the video where the answer was discussed.
---
By using the `useReducer` hook exclusively.
```js
const <formData, setFormData> = useState({
name: "",
username: "",
email: "",
});
```
### --feedback--
Think about a way to track different pieces of state independently.
Review the end of the video where the answer was discussed.
---
By calling the `useState` hook multiple times.
```js
const [formData, setFormData] = useState({
name: "",
username: "",
email: "",
});
```
## --video-solution--

View File

@@ -2,7 +2,7 @@
id: 67d1eb6929e68117faa6717f
title: What Is Rendering in React, and How Are Components Displayed on the Screen?
challengeType: 11
videoId: nVAaxZ34khk
videoId: KLWTruxP1a8
dashedName: what-is-rendering-in-react-and-how-are-components-displayed-on-the-screen
---
@@ -10,6 +10,58 @@ dashedName: what-is-rendering-in-react-and-how-are-components-displayed-on-the-s
Watch the lecture video and answer the questions below.
# --transcript--
What is rendering in React, and how are components displayed on the screen?
In React, rendering is the process by which components appear in the user interface (UI), usually the browser.
React takes all your JavaScript, JSX, and CSS code, figures out how it should look, and then displays it in the user interface.
The rendering process consists of three stages: trigger, render, and commit. Let's take a look at these in more detail.
The trigger stage occurs when React detects that something has changed and that the user interface might need to be updated. This change is often due to an update in the state or props.
For instance, noticing that it's time for dinner can trigger you to go into the kitchen to start cooking.
In the `Counter` example below, clicking the increment or decrement button triggers React to show the new `count` value:
```jsx
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
```
Once the trigger happens, React enters the render stage. Here, React re-evaluates your components and figures out what to display.
To do this, React uses a lightweight copy of the "real" DOM. This is called the virtual DOM. With the virtual DOM, React can quickly check what needs to change in the component.
Think of this stage as the point where you're in the kitchen, you've gathered your ingredients, and you cook your dinner.
For the `Counter` component, the render stage is the point where React runs the functions again with the new `count` value. React recalculates what the `<h1>{count}</h1>` part of the component should look like based on the updated `count` value, but you won't see any changes on the screen until the next stage commit.
The commit stage is where React takes the prepared changes from the virtual DOM and applies them to the real DOM. In other words, this is the stage where you see the final result on the screen.
To make this happen, React compares the virtual DOM to the actual DOM, identifies only the parts that need updates, and applies those changes to the real DOM to update the user interface.
You can think of this stage as the point where you serve the food you cooked, making it visible just like React does when it commits updates to the actual DOM.
As for the `Counter` component, the commit stage is the point in which the new `count` value is applied to the `h1` element, and you can see the change on the page.
These three processes are extremely fast because React minimizes direct DOM manipulation by calculating changes in the virtual DOM first, then it updates only the parts that need to change in the real DOM.
# --questions--
## --text--
@@ -22,7 +74,7 @@ Start, load, and finish.
### --feedback--
Think about the steps React takes to display and update components.
Review the beginning of the video for the answer.
---
@@ -30,7 +82,7 @@ Initialize, update, and complete.
### --feedback--
Think about the steps React takes to display and update components.
Review the beginning of the video for the answer.
---
@@ -42,7 +94,7 @@ Begin, process, and end.
### --feedback--
Think about the steps React takes to display and update components.
Review the beginning of the video for the answer.
## --video-solution--

View File

@@ -2,7 +2,7 @@
id: 67d1ebb595f4f619c0e35d1a
title: How Do You Update Objects in State?
challengeType: 11
videoId: nVAaxZ34khk
videoId: BwHJrBW-m0M
dashedName: how-do-you-update-objects-in-state
---
@@ -10,6 +10,157 @@ dashedName: how-do-you-update-objects-in-state
Watch the lecture video and answer the questions below.
# --transcript--
How do you update objects in state?
Updating objects in state in React can be tricky if you're used to changing object property values directly.
React treats state as immutable, meaning you should not modify it directly.
Let's look at what happens if you try to change objects in React state directly, and then dive into the correct way to do it.
Let's say you have an object in your component state that represents a user's profile, and you want the user to update their age:
```jsx
import { useState } from "react";
function Profile() {
const [user, setUser] = useState({
name: "John Doe",
age: 31,
city: "LA",
});
// Change user age directly
const handleAgeChange = (e) => {
user.age = e.target.value;
console.log(user);
};
return (
<div>
<h1>User Profile</h1>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<p>City: {user.city}</p>
<h2>Update User Age </h2>
<input type="number" value={user.age} onChange={handleAgeChange} />
</div>
);
}
export default Profile;
```
This code will not work because you're directly modifying the `user.age` property.
Even though `console.log(user)` will show the new age in the console, React won't re-render the component to show it in the user interface because you didn't use the setter function, `setUser`.
To update an object directly in the state, you need to use the setter function to create a new object with the updated value. For example:
```js
const handleAgeChange = (e) => {
setUser({
age: e.target.value,
});
};
```
That works. But if you look at the page now, the user's age gets updated, but the values for the name and city are lost.
This is because the new object you passed to the setter function only contained a key/value pair for `age`.
To prevent this from happening, you can copy the existing object first, then update only the property you want to update, in this case, `age`.
To do this, you can pass a special function called an updater function to your setter function, `setUser`. The updater function takes the pending state as an argument, here, called `prevUser`, and should return the next state:
```js
const handleAgeChange = (e) => {
setUser((prevUser) => {
const updatedUser = { ...prevUser, age: e.target.value };
console.log('Previous State:', prevUser);
console.log('Updated State:', updatedUser);
return updatedUser;
});
};
```
As you can see, we create a new user object called `updatedUser` by using the spread syntax to copy the pending user object, `...prevUser`. We then update the age based on the form input and return `updatedUser` at the bottom of the function as the next state.
Now your project works as expected, and updates to the age input don't affect the user's name or city name. You can also see the previous and updated states in the console.
This is the ideal way to update an object in state, especially when you're not updating all the properties.
To update the remaining `name` and `city` properties, you can write them as separate setting functions and connect them to their respective inputs:
```js
const handleNameChange = (e) => {
setUser((prevUser) => ({
...prevUser,
name: e.target.value,
}));
};
const handleCityChange = (e) => {
setUser((prevUser) => ({
...prevUser,
city: e.target.value,
}));
};
```
Or you can combine them into a single setter function like this:
```js
const handleChange = (e) => {
const { name, value } = e.target;
setUser((prevUser) => ({
...prevUser,
[name]: value,
}));
};
```
To make this work, each input field has to have a `name` attribute.
Here's the full code now:
```jsx
import { useState } from "react";
function Profile() {
const [user, setUser] = useState({ name: "John Doe", age: 31, city: "LA" });
const handleChange = (e) => {
const { name, value } = e.target;
setUser((prevUser) => ({...prevUser, [name]: value}));
};
return (
<div>
<h1>User Profile</h1>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<p>City: {user.city}</p>
<h2>Update User Age </h2>
<input type="number" name="age" value={user.age} onChange={handleChange} />
<h2>Update User Name </h2>
<input type="text" name="name" value={user.name} onChange={handleChange} />
<h2>Update User City </h2>
<input type="text" name="city" value={user.city} onChange={handleChange} />
</div>
);
}
export default Profile;
```
# --questions--
## --text--

View File

@@ -2,7 +2,7 @@
id: 67d1ebcab4e0521a6654bb64
title: How Do You Update Arrays in State?
challengeType: 11
videoId: nVAaxZ34khk
videoId: HviNQSO369k
dashedName: how-do-you-update-arrays-in-state
---
@@ -10,31 +10,174 @@ dashedName: how-do-you-update-arrays-in-state
Watch the lecture video and answer the questions below.
# --transcript--
How do you update arrays in state?
In React, updating arrays in state is quite straightforward, but it can be easy to make a mistake, especially if you're coming from vanilla JavaScript where you can modify arrays directly.
In React, state is treated as immutable so it can recognize changes and make the proper updates to the user interface.
Let's look at how you can update arrays held in state in React.
One of the most common mistakes when updating arrays in a React state is to directly modify the array using methods like `push()`, `pop()`, or `splice()`. These methods mutate the original array, and React does not allow that.
React relies on a new array reference to detect changes, so directly modifying the array can prevent the component from re-rendering as expected.
Here's an example of using the `push()` method to add to an array in state, which won't work:
```jsx
import { useState } from "react";
function ItemsList() {
const [items, setItems] = useState([
{ id: 0, name: "Item 1" },
{ id: 1, name: "Item 2" },
{ id: 2, name: "Item 3" },
]);
const addItem = () => {
const newItem = { id: items.length + 1, name: `Item ${items.length + 1}` };
items.push(newItem); // This modifies the original array
setItems(items); // React will not detect this change
};
return (
<div>
<button onClick={addItem}>Add Item</button>
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default ItemsList;
```
If you click the `Add Item` button, nothing happens in the user interface.
It might also be tempting to remove items from the array with the `pop()` method:
```js
const removeItem = () => {
items.pop(); // Modifies the original array
setItems(items); // React will not detect this change, either
};
```
To update an array in state, the key is to create a new array, do your operations, and pass that to React, rather than mutate the existing array.
Because it's a new array, React will know that the state has been changed, and trigger a re-render.
Here's how you can add to the `items` array using the spread operator:
```js
const addItem = () => {
const newItem = {
id: items.length + 1,
name: `Item ${items.length + 1}`,
};
// Creates a new array
setItems((prevItems) => [...prevItems, newItem]);
};
```
`[...prevItems, newItem]` creates a new array by copying all items in the existing `items` array held in state, then adds `newItem` at the end, which increments the `id` and the item number.
If you want to remove something from the array, you can use the `filter()` method, which returns a new array after filtering out whatever you want to remove:
```js
const removeItem = (id) => {
setItems((prevItems) => prevItems.filter((item) => item.id !== id));
};
```
Here's the full code:
```jsx
import { useState } from "react";
function ItemsList() {
const [items, setItems] = useState([
{ id: 0, name: "Item 1" },
{ id: 1, name: "Item 2" },
{ id: 2, name: "Item 3" },
]);
const addItem = () => {
const newItem = { id: items.length + 1, name: `Item ${items.length + 1}` };
setItems((prevItems) => [...prevItems, newItem]); // Creates a new array
};
const removeItem = (id) => {
setItems((prevItems) => prevItems.filter((item) => item.id !== id)); // Creates a new array
};
return (
<div>
<button onClick={addItem}>Add Item</button>
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name}{" "}
<button onClick={() => removeItem(item.id)}>Remove</button>
</li>
))}
</ul>
</div>
);
}
export default ItemsList;
```
Those are some common ways you can update an array in state.
# --questions--
## --text--
How should you NOT update an array in a React state?
Which of the following is the correct way to update state and add new items to an array?
## --answers--
By creating a new array with the updated values.
---
By using the `concat()` method to add new items.
---
By spreading the existing array and adding new items.
---
By directly modifying the array with the `push()` method.
```js
setItems(copy [prevItems, newItem]);
```
### --feedback--
React relies on immutability, so avoid direct modifications.
To update arrays in state you need to use the setter function and proper syntax for adding new items to an array.
---
```js
setItems(new Array = [...prevItems, newItem]);
```
### --feedback--
To update arrays in state you need to use the setter function and proper syntax for adding new items to an array.
---
```js
items = (prevItems) => [...prevItems, newItem];
```
### --feedback--
To update arrays in state you need to use the setter function and proper syntax for adding new items to an array.
---
```js
setItems((prevItems) => [...prevItems, newItem]);
```
## --video-solution--