React Context & Hooks Tutorial #10 - useState Hook

Net Ninja · Beginner ·🌐 Frontend Engineering ·7y ago

Key Takeaways

Introduces the useState hook in React, demonstrating how to use state in functional components

Full Transcript

okay then so right now we have this functional component right here which renders this small lists of songs now I don't want these to be hard-coded these songs I'd like them to be stored in States and then dynamically out put them in a template now normally to use states inside a component it would have to be a class component but now with react hooks like I've said before we can now use states inside a functional component like this as well and we do that by using a hook called use States now that hook is just a function and it's going to allow us to use a piece of state inside this functional component so let's start off by importing that hook up at the top so comma then we won't use States from react as well so we'll use this hook at the top so we'll say use States like so so we're just invoking a function that's all we're doing here now this hook accepts an argument which is going to be the initial value for this piece of state that we want to use so like in a class component we say something like you know state is equal to an object where we define different properties what we're essentially doing is defining a property of state inside this function now so I want to define some songs inside an array and that's going to be the initial value of this piece of state inside this components so I'll do in a rate first of all then I'll go to a new line just to give myself some room and I'm gonna do an array of songs in here now I'll just paste these in it's literally three objects very simple and each object represents a single song it has a title and each one has a unique ID as well so we have these three objects now stored in this array as the initial value for this piece of state so this function returns an array and inside that array that it returns to us there's two values the first value is going to be the actual data the piece of state itself and the second value is going to be a function which we can use to edit that piece of state so it returns those two values inside an array so we can use array destructuring to get these two different values I'm gonna say Const and then array is equal to this thing right here and the two properties we can call what we want but typically I name them whatever the state is whatever that defines so for example songs so I'm gonna call the first property songs and the second one is going to be set whatever I call it so set songs in this example so now we have the dates itself and also a function to change the data and now this is the state for this property inside this component and we can use it inside this component now we can use songs to reference this array of data so now we can cycle through that inside the template down here so that we don't have to hard code it instead I'm going to say songs dots map because we're going to map it to a new array of HTML templates and inside this function we'll take the song each time around so it's going to cycle through the array perform a function for each one in that array each item and each time we reference that by song so now we can return some JSX for each element so return and then in parentheses and just gonna say first of all Li and inside the Li tag I want to output the title property of the song so I'll say song title and then also when we cycle through things like this react expects us to provide a key property which is unique for each element as well and that's why I added this ID property right here so it will say song dots ID for them so now we're cycling through that state and without putting a bit of template for each one of them so now let me see if this works I'm going to save it and come over here to the browser and now we can see all of those things out here in the browser so that's worked now we can use this state inside a functional component which is pretty awesome just using this one hook use state okay so say we want to change the data say for example we have a bottom down here which when we click it it adds some kind of new song so first of all let's create that bottom I'm going to say button right here and in there I'll say add a song we'll need to attach an on-click event handler to this and that is going to reference a function called add song which will create now so let's create this function over here we'll say Const add song and set that equal to an error function and inside this function what we want to do is change the data now remember I said that this function that we get back from used a is used to change the data so all we need to do inside here is say set songs which is what we called the function and then inside here we pass whatever value we want this data to be now we still want it to be an array so we pass in an array and this is going to completely replace whatever the current value of songs is inside here okay so we can't just add something extra into this we have to output the whole thing because it's going to completely replace it so for that reason we need to use spread syntax like this to say get the current songs and spread them into this array so it's going to grab each one of these and put them into this new array and then we want an additional item in this new array so that's going to be a new object which will have a title property and this is just going to be like new song and then an ID property it will just say that's for for now because we have one two three already so now hopefully when we click on this button it's going to run this function it's going to use this set song's function which we get back from use state right here so we can change the state we're passing in a new array which is going to completely replace the current array the current value of songs so we're spreading the current elements out inside that new array and then adding a new one as well so let's give this a whirl I'm going to save it and come over here and click add song and now we get new song over here it works but watch this if I add a new song again we should get some kind of warning or error and we do and that's because each time we add a new song we give it this value ID a4 and when we cycle through those songs and we output those then we're saying the key is the ID property so every time we add and song and he updates there it's still getting ID for for each element now react wants these keys to be unique for each different element it outputs so we can't just hard code it's before every single time so we need some kind of way to generate a unique ID for each new song fortunately there is a package that we can do that really easily with so I'm gonna go to a new console and let me just play this so I can see what I'm doing and then I'm going to install a package now first of all I need to CD into hooks up so CD hooks up and then I'm going to install a package called UUID so npm install UUID okay so once we've done that we just need to import it at the top so I'll say import and it's going to be UUID from and it's UUID and /v 1 there's different versions we can use I'll just use v1 for now and then we just need to use that down here and all we do is invoke this which is a function and that generates a unique ID for is every time around so every time we add a new song it's gonna be something different so instead of hard-coding this to be for now I'm gonna say uhyou ID which is this function we just imported and then invoke that to create that new unique ID so save it and come over here and now if we add a new song and a new one and a new one we no longer get that error and if we go to react over here and open this up and go to the song list we can see all of these Keys are now unique so it's generating these forests so anyway there we go my friends now we have used this hook use state to use some state inside our functional component and that is pretty awesome because we could never do this in the past we'd always have to use a class component to use State but now all it takes is one simple function one hook use state to do that now inside a functional components so remember this returns two things the actual value of the state and a function to change that value this accepts a parameter which is the initial you of that piece of state as well and then we just use it as normal inside the component

Original Description

Hey gang, in this React hooks tutorial we'll take a look at our first hook - useState. The useState hook allows us to use state in a functional component. ---------------------------------------- 🐱‍💻 🐱‍💻 Course Links: + Course files - https://github.com/iamshaunjp/react-context-hooks + Complete React Course - https://www.youtube.com/playlist?list=PL4cUxeGkcC9ij8CfkAY2RAGb-tmkNwQHG + React Context Docs - https://reactjs.org/docs/context.html + Modern JavaScript Tutorial - https://www.udemy.com/modern-javascript-from-novice-to-ninja/?couponCode=NINJAYT 🐱‍💻 🐱‍💻 Other Related Courses: + Firebase Firestore Playlist - https://www.youtube.com/watch?v=4d-gIPGzmK4&list=PL4cUxeGkcC9itfjle0ji1xOZ2cjRGY_WB Firebase Authentication Tutorial - https://www.youtube.com/watch?v=aN1LnNq4z54&list=PL4cUxeGkcC9jUPIes_B8vRjn1_GaplOPQ
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

Related AI Lessons

Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →