This course teaches you about state and the useState hook. State is component-specific memory.
Learning Objectives
- Learn what state is
- Learn how to implement the useState hook
- Learn how to work with state within an event handler function
Intended Audience
- This course is intended for anyone who wants to learn about React
Prerequisites
- Recommended: React: Introduction to Event Handling
- Recommended: React: Introduction to Rendering Lists
React: Introduction to State and useState. And I am Farish Kashefinejad, the software development domain lead at Cloud Academy. If you have any questions or concerns about the content in this video, feel free to reach out to support@cloudacademy.com. I will begin this video by going over the setup. On the left side of the screen, I have the Cloud Academy lab environment with the code for a React application. On the right side of the screen, I have the React development server running in the browser. While typing, you may see an error on the right side of the screen, this is due to autosave being enabled and saving before my code is completed. Now a quick overview of the files for this application on the left. There is a app_gsx file that imports a List component. The List component imports a ListItem component. There's also a array named users imported from this data file. Each element of the array is an object with two properties, a username, and a unique id.
Currently, the user's array is iterated by using the map method, and the map method returns the list item component, passing the users username as a user prop. Now, the ListItem component has the user prop which is used to display the username on the right through this gsx expression, along with this Delete button which is also displayed to the right of the username. The goal for this video is that when the Delete button is clicked, the corresponding username is deleted from this list. To accomplish this goal, I need to use state. What is state? State is component-specific memory that allows us to manage changing data in our React application. State is the data a component needs to keep track of. A component can create, update, and use state as the data changes. How is state different than props? Props represents immutable data, as in it is unchangeable. Props reflects a component's data at a given point of time when passed through from a parent component to a child component.
When you have a React application that needs to respond to users input, input that changes the data, or the nature of the React application through that interaction, you need to use state. Transitioning to the list component. To work with state, I need to use a React hook that is a useState. On the first line where the React input statement currently is, I will add a comma after React and then destructure useState from React. When setting up state, state is created by using a destructured array syntax. I will begin by typing const[] and this use state array has two elements.
The first element is the name of the state, which I will call currentUsers, and currentUsers will be what the component will reference for data moving forward once I complete the setup. The second element is the name for the setter function for that state. When it comes to naming conventions, a common practice is that the setter function will begin with the word set followed by the state name. So, I will name this setCurrentUsers. And I now need to set this destructured array syntax equal to useState(). When it comes to useState, I can set a default value of the state inside of the parentheses. It can be blank as in undefined, but for now I will pass the users array from that data file. And this could be referred to as the default state or the initial state of the component. So, the initial state of this component is that array of users. This means that the current users is storing that array of users. So, moving forward, I'm not going to be using the users array directly anymore, I'm going to work off the state currentUsers.
Now, because the Delete button needs to respond to a click, next I'm going to create an event handler function. The purpose of this function is that when the Delete button is clicked, the corresponding user id is passed through and that user will be deleted from this list. The id is going to help me find that user in order to remove it from the state. I will type const handleClick = arrow function with the argument of id. Inside of the arrow function, I will use the filter method to filter out the user with the id that is passed as an argument, const filteredUsers = currentUsers.filter(). Note I'm using the state array here, not the users array. Inside of the parentheses, I will pass through an anonymous arrow function with an argument of user, and that arrow function will return any user that has id that does not match the ID that was passed through as an argument. Going over the structure of this event handler one more time. So, when the Delete button is clicked, the corresponding user id will be passed through as an argument. The filter method will be called on the currentUsers state array. The filtered users will equal a new array of users without the user with the matching id, thus removing that user from the array. This is how the deletion will be performed. Now, once this is completed, you need to update the state with this filtered users array which represents a new state.
And I will need to use the setter function to accomplish this. SetCurrentUsers() and I will pass in the argument of filtered users. When the button is clicked after everything else is done, the state will be updated with new information. Now, the event handler function is done. I need to adjust this map method below which generates the list to work with state. This part is easy. I will replace Users with currentUsers. Now, this map method is relying on the state and no longer using just a array of data. Now that this part is done, I need to attach the event handler function, the handleClick function that I created earlier to the list component. That way, when the Delete button is clicked, I can reference this function and the corresponding user to capture that ID and pass it as an argument. One thing to point out here, I already have this key prop which is required by React when rendering lists and this key prop uses the user id. So, I can pass the same value as the argument. To begin, I'm going to create a new prop called handleClick which is the same name as the event handler function because I want to emphasize that as I'm passing this through props, this is the function that it is referencing, I will set it equal to an anonymous function that will return handleClick with the argument of the user.id.
So, why is handleClick wrapped inside of that arrow function? When React renders a component, it immediately executes in a JavaScript. In this case, if I were to directly call the handleClick function with the user id inside of the prop when the component renders, this function would execute, thus deleting all the users. To prevent this when working with React, functions need to either be referenced inside of props not called or wrapped inside of an anonymous arrow function. Now this completes the setup needed for the list component with the state and the event handling function. I will go to the listItem component in order to set up event listener and access the handleClick props. Looking at the argument for the listItem component, the user prop is currently destructured from the props object. So, I will add a comma after user and type handleClick to destructure that out of the props object. Now, I need to have this component assigned for any mouse clicks specifically on the button. On the button, I will add a onClick prop and set it equal to handleClick.
And that is all the code needed for the listItem component. On the right side, I will click the' Delete' button a few times. And the corresponding user for each button is being removed from the list on the page. So, why does this work? When the Delete button is clicked, it triggers the handleClick function that has been passed as a prop from the list component. The state is then updated with a new list of users, and whenever the state changes, React rerenders any components associated with that state. And that's it. Thanks for watching at Cloud Academy.
Farish has worked in the EdTech industry for over six years. He is passionate about teaching valuable coding skills to help individuals and enterprises succeed.
Previously, Farish worked at 2U Inc in two concurrent roles. Farish worked as an adjunct instructor for 2U’s full-stack boot camps at UCLA and UCR. Farish also worked as a curriculum engineer for multiple full-stack boot camp programs. As a curriculum engineer, Farish’s role was to create activities, projects, and lesson plans taught in the boot camps used by over 50 University partners. Along with these duties, Farish also created nearly 80 videos for the full-stack blended online program.
Before 2U, Farish worked at Codecademy for over four years, both as a content creator and part of the curriculum experience team.
Farish is an avid powerlifter, sushi lover, and occasional Funko collector.