Transcript for:
Introduction to ReactJS

hey what's going on everybody it's your bro hope you're doing well and in today's video I'm going to show you everything you need to know to get started working with reactjs so why don't you go ahead and sit back relax and enjoy the show react is a JavaScript library not framework that's used to easily build and arrange user interfaces for web applications react focuses on building a web application using these things called components a component is a self-contained section of code that functions as as a reusable building block think of Legos you could say a Lego is similar to react component each Lego represents a section of reusable JavaScript and HTML code we can build a diarama or other complicated structure from these Legos if we use enough of them and in the correct places react uses a syntax extension of JavaScript known as jsx meaning JavaScript XML jsx allows you to write HTML like code within your JavaScript files react also utilizes a virtual Dom it's a lightweight version of the real Dom of a web page we can keep track of any changes made to the virtual Dom and only apply that specific change to the real Dom without needing to refresh the entire web page only that specific section this reduces rendering performance overhead before we do begin you will need to know JavaScript since react is a JavaScript library everything up to arrays classes objects and es6 feature such as Arrow functions will be necessary HTML will also be mandatory since our react components involve rendering HTML elements and applying CSS I do have full free courses on my YouTube channel on these topics if you need to catch up or you need a refresher so that's a quick overview of react we'll move on to the installation instructions next we're going to download nodejs from this URL nodejs.org node.js is a backend JavaScript runtime environment it executes JavaScript code outside of a web browser we're mostly interested in the node package manager that comes with it let's download the latest version of node.js open it when the download is complete select next read the license agreement yes I did read it that fast next select a destination folder I'll keep it as is you can define a custom setup but that's outside of the scope of this tutorial series we'll press next we'll skip tools for Native modules press next and install then finish you'll also need a text editor I recommend vs code since you've made it this far in my web development series I'm assuming you already have one downloaded which you can get from this site code dovisual studio.com and select the correct download for your operating system within VSS code I'm going to create a project folder let's go to explore open folder just for convenience I'll place my project folder on my desktop I'll create a new folder I'll name mine website then we will select this folder we're going to need to open up command prompt if you're using Windows or terminal if you're on Mac you can also do this within vs code go to the hamburger menu up top terminal new terminal we within our website folder we will type the command npm meaning node package manager create vit at latest meaning latest version V's a development server it's a modern replacement to create react app which is now outdated hit enter we'll need a name for this project a common naming convention for a user's first react project is my react app that's a common name that you'll see enter select a framework using the arrow keys we can select whatever framework we would like to use we will select react hit enter are we going to use typescript or JavaScript we'll stick with plain JavaScript all right here are the last few commands and they are given to us we'll change the directory to our react app CD meaning change directory my react app and that's the name of the folder where our project is located npm install that is the second command the last command is npm runev to start the development server npm runev all right so our web server is found at this address let's copy it then open up a web browser let's paste that address and here we are within our development server this is a sample project that's given to us it even includes this little counter hey this is future bro I was editing this video and I totally forgot to mention how you can restart the server if you close out of it all you got to do is open up a terminal let's go to terminal new terminal we have to be sure that we're within our application folder I'm going to change my directory by typing CD the name of the folder my react app then npm run Dev to start the development server and let's refresh that yep it seems like it's working so yes I forgot to mention that that is all I'm quickly going to cover the project structure of our react application we'll begin with the node modules folder this folder contains external libraries and packages that our project relies on a few of which are build tools utility libraries routing libraries just to name a few we won't be spending any time directly in this folder but you should still be aware what it's for if it just contains external libraries and packages that our project relies on next we have the public folder the public folder contains any public assets one of which in here is a vit image it should be this image right here this folder can contain public fonts images videos they're not bundled during the final output they're typically available via a URL just to demonstrate I'm going to delete this image file and see what happens yep and that logo is gone so my vit logo was a public asset via a URL and let's put that back then we have the source folder we'll spend 99% of our time within the source folder we have an assets folder that can contain images and videos the assets folder is very similar to the public folder but files within the assets folder are bundled during the final output public assets are not and they're generally available via a URL my re act image is within the assets folder currently we have a main jsx file remember that jsx is Javascript XML in a way this functions as our main Javascript file react works with components we're adding a single component an app component which we are importing so let's take a look at our app component the app component in this example you could say is the root component we have two different stylesheets a stylesheet for app and we have an index CSS stylesheet this is the main CSS file for our application we're importing this file from our main jsx file right here so that's the source folder then we have an index HTML file this is the main entry point into our program within the body of our document we have a development with an ID of root as well as a script to our main jsx file a few other things you should know about is this package Json file Json file files are structured in key value pairs this file contains metadata about our project such as the project name the version number what build we're using we're using vit and the react version number just to name a few all right everybody so in just a moment we will be creating our first react component we already do have one component that is app right now this is serving as a sample project for us then we are importing app to main jsx this is our main J s x file think of it as the main JavaScript file we are creating a root element and including our app component within our app component we do have a function delete everything within this function that should eliminate our sample project and we no longer need these Imports we can delete them too but you do want to keep this export statement components can have dedicated stylesheets which you can see here for app CSS we are going to delete this because we no longer need it we do have an app component that's going to serve as the root we will add other components to our app component our app component ties them all together to create a new component go to your Source folder we're going to rightclick then go to new file we will create a component for a header the extension is jsx because it's a JavaScript XML file we will be working with function based components we will create a function with the name of header do pay attention to the capitalization then we would like to export this component so we can import it elsewhere at the end of this file type export default the name of the component header within our header function we can write a combination of JavaScript and HTML all we're going to do within this function is return something return parentheses semicolon within the return statement you can write pure HTML I will create a header element so react components they're only capable of returning a single element but you can place children elements within within our header element I will create an H1 element with text of my website just to be sure everything is working let's save I'm holding contrl s on Windows we will go to our app component then import the header component So within app we will type the statement import the name of the component header from a location that location is going to be do SL header. jsx we can now use this header component within our app component we will also be returning something so we will need a return statement return parentheses semicolon what are we going to return I would like to use my header component so to add a component we need a set of angle brackets then type the name of the component header like this they're a pair of two and the second one is closed that's why we have a forward slash preceding it we now have a header component you can shorten the syntax as well take your component end it with the forward slash that also works too it's a shorthand way of writing the same thing let's head back to our header component We'll add a few more elements after our H1 element let's create a navigation element then within the navigation element we'll create an unordered list within the unordered list we'll create a few list items the first will be home these are list items you would typically see for a navigation bar home about services and contact we now have our unordered list I'll enclose our list items within anchor tags to make them hyperlinks a hre equals I don't want these to go anywhere I'm just going to leave these empty I'll add a pound sign and then be sure to close these anchor tags we'll place our text within the anchor tag so they are now hyperlinks okay let's do that for the other list items there we are then after my navigation element I will add a horizontal rule to make it look nice okay there is our header component we no longer need to work with this header component we do have some styling already applied those Styles can be found within index.css if you would like to start fresh and eliminate all of these Styles you can delete everything from here then you do have HTML with no CSS in a future video I'll show you various ways in which we can apply CSS to a react component but for now we'll just keep this the same our head element is now complete we will create a new element for a footer again go to our source folder right click go to new file footer. jsx we are creating a function based component it's a function that's going to return a footer component then at the end of our script we will export default the name of the component footer so that we we can import it elsewhere our footer is going to return something so we need a return statement then within the set of parentheses we can return a single element we will return a footer element but remember you can place children elements within an element it still only counts as one then so what do we want to do for our footer I'll include a paragraph element within the paragraph element I'm going to add a copyright symbol to add a copyright Mark Type ampersand copy semi call in then afterwards I'll add your website name all right now we need to import this footer going back to our app component we will import footer from footer. jsx then I would like to include a footer component after the header now pay attention to this we're returning two components we have this warning we only have the capability of returning a single component that's how our return statements are designed jsx elements must be wrapped in an enclosing tag do you want a jsx fragment so since we only have the capability of returning a single enclosing tag we're we're going to enclose our components with what's known as a fragment it's just an empty set of ankle brackets so we will enclose all components within a fragment and that should work we have our footer component following our header component we have our header and our footer let's make a few more changes to our footer I'm going to zoom out a little bit within our return statement we can insert some Javas script to insert some JavaScript you need a set of curly braces I will create a new date object this is some JavaScript code new date parentheses I would just like the year I will follow this object with get full year method let's save and take a look so I'm filming this video near the end of 2023 your web application should return the current year when ever you're watching this all right our footer component is now done I'm going to create a component for a unordered list to sandwich between our header and our footer I'll create a component for food we will go to our source folder create a new file this component will be food. jsx again we are creating a function based component with the name of food then we will export this component when we're done export default food be sure to add a return statement before we add anything to the return statement I will create some JavaScript variables so normally if you're adding JavaScript code within the return statement you need a set of curly braces but outside of the return statement you don't I will create two JavaScript constants const food one pick some food for me I will pick an orange let's make that Capital all right then let's create a second food variable food 2 for me will be a banana within the return statement we can utilize these constants what do we want to return exactly I will return an unordered list we'll have a few list items three to be exact my first list item I'll just add some text I'll add an apple just to be sure that everything is working let's import this food component from our app component again we need an import statement import food from food. jsx we can now use the food component we will add that after the header we will add food then here is our first list item an apple okay let's head back to our food component for our second list item I will add food one that's our constant now pay attention to this if I type food one well we're literally printing the text food one since we're within our return statement I would like to include some JavaScript code we're including a JavaScript variable so I need to enclose this variable within a set of curly braces because we're within the return statement and now now my second list item is an orange then let's include food 2 but I'm going to add one more thing food 2 however I'm going to use the builtin 2 uppercase method just to demonstrate that we can use JavaScript functions all right and there is our unordered list we have an apple orange and a banana so these components are now complete and the cool thing about react as well is that we can keep on reusing these components if we would like I would like a couple food components so I will just paste another component we now have two food components or even three or four you can rearrange these components however you would like by rearranging them we can change the feel and style of our web application for demonstration purposes I will put our footer on the top that doesn't make any sense but I just want to demonstrate so our footer is now on the top followed by the header then the food component or maybe I would like the food component on top we now have our food component footer component then our header component all right everybody that is an introduction to react react is all about reusing components a component is a small section of code that can include JavaScript and HTML your function will return that code and make it reusable and that is your introduction to react hey what's going on everybody and today's video I'm going to get a little more in depth with creating components and by the end of this topic we will be creating our own card component so sit back relax and enjoy the show in today's topic I'm going to get a little more in depth with react components as we've discussed in the previous topic a component is a section of reusable jsx code it's HTML like code that can contain JavaScript I thought today we could create some card components card components are fairly popular with react app applications typically they involve a picture a title and a description you can use cards for all sorts of things in the previous topic we did delete all of the contents within our app function let's go ahead and do that now if we haven't already and we'll delete these Imports we will not need them for this lesson in the previous topic we did have a stylesheet for our app component we can delete this too we are now ready to begin within our source folder we will create a new file the name of the component will be card this is a jsx file jsx meaning JavaScript XML our components will be function based function type the name of the component card parenthesis then curly braces we will be exporting this component so that we can import it elsewhere so type export default the name of the component card within our card function we will be returning some HTML like code we'll begin with the div element we will be applying some CSS Styles we will need to set the class however with jsx class is a reserved keyword to set an elements class we have to instead use class name do pay attention to the capitalization the N is uppercase okay we will set this div section equal to card so cards typically have an image we'll include an image element we'll set the source later they usually have a title we'll use an H2 element and a description we'll include a paragraph for our H2 title why don't you go ahead and type in your name I'll type in my YouTube channel name but feel free to use your own name then let's add a description for the description of Year card type in what you do for a living or if you're a student what are you studying for me personally I make YouTube videos and add a hobby of viers I make YouTube videos and play video games so far so good let's import our card component just to be sure that it's working within our app component I will at the top import the name of the component card from a file location these files are right next to each other so I will type SLC card. jsx within our app component we will return within the return statement list the component we would like to return we will return our card component to include a component within angle brackets type the name of the component these are typically in pairs you need an opening tag and a closing tag and there's our card so far we'll be applying some CSS styling momentarily there is a shortcut in place of using an opening and closing tag take the opening tag end it with a forward slash that's also valid let's head back to our card component we'll include an image within our opening image tag it is good practice to set the alt attribute just in case this image can't be displayed or if somebody is using a screen reader the alternate text will be displayed or read out loud will include a profile picture for us let's set the alternative text to be profile picture we're going to set the source attribute now I recommend pausing the video and finding a profile picture of yourself from you know Facebook or Twitter or whatever you use for social media pick a smaller picture something around 200 x 200 pixels would be decent if you don't want to follow along you can include a placeholder image just for this lesson which you can get from this site this will be an external URL https colon to slashes Via placeholder doc1 15 that will give you a placeholder image otherwise if you have an image you would like to use I'm using the profile picture from my YouTube channel all we got to do is place this image within our assets folder from our card class we will import that image import then we need a name for this import I'll name my import profile pick from a location so we need to navigate to the assets directory then get our image slash the assets directory slash the the name of the image so mine is profile and it's a JPEG yours is likely going to be different do pay attention to that profile. jpeg for the source attribute I will set the SQL to a set of curly braces then we will include our profile pick that we're importing there's my profile picture depending on the dimensions of your profile picture it might be fairly big you may want to choose a smaller image or otherwise within our CSS file we can change the dimensions of the picture okay let's head to our CSS stylesheet we already do have some Global CSS properties already applied but I'd like to start fresh let's delete everything within the CSS stylesheet that should eliminate all CSS within our web page we will select the name of the class card remember that with jsx we use class name not class with within our index CSS stylesheet let's select our card class I'm going to go through these CSS properties real quick we should already have some experience with CSS okay let's add a border border one pixel solid I'll set this to be black I do like using hsl values I'll pick a light gray color let's set the lightness to about 80 for the Border I'll set the Border radi to be 10 pixels to round the corners the corners should now be rounded as you can see here I'll add a box Shadow the first value is for the horizontal offset the second is for the vertical offset the third value is for the blur radius I'm going to pick a lighter color though so I'm going to select black change this to an hsl value but I'm going to change the transparency to be 10% so 0.1 that is not bad looking okay let's add a little bit of padding 20 pixels padding is found between the elements and the border so if I were to increase this we have more padding but let's stick with 20 I'll add some margin margin is for the space outside of the Border let's go with 10 pixels I'll text align Center to Center the elements within text align Center I'll set a Max width for the card to be 250 pixels then I will set the display to be an inline Block in case we have more cards they'll at least flow within our container if we have more because normally divs are Block Level elements okay so let's work on the card image next we'll head back to our card component class we'll add a class name to the image element class name equals let's say card image go back to our CSS stylesheet we are accessing our cards class then access the card image class within I will set a Max width I will set a Max WI width to be 60% of the width available I will set the height to be Auto to automatically resize if you would like a circular image you can set the Border radius to be 50% I'll add a little bit of margin on the bottom with margin bottom 10 pixels all right let's work on our title next going back to our card component let's add a class name the class name will be card- title going back to our CSS stylesheet we will select our card class then select the card title class with my card title I will set a font family to be pick a font I like Ariel I'll set a backup of s serif in case Ariel can't be displayed for some reason I'll set margin to be zero to remove any margin I'll set the text color to we'll set the color property to be pick a color again I'm using hsl values I'll set the lightness to be 20% now let's change our card text going back to our card component within our paragraph element we will set the class name to equal card- text going to our CSS stylesheet we will access the card class then access the card- text class I'll set the font family to be aerial as well and I will change the color I'll set the lightness to be 40% again I'm using hsl values uh maybe 30 I would say that looks decent enough we have now created and styled a card component within our app component we can reuse the card component however if I were to add another Well jsx elements must be wrapped in an enclosing tag our return statements are only designed to return a single element you can enclose all elements within what is known as a fragment it's an empty set of angle brackets then technically we're only returning a single El element we now have two cards however they are identical though and we can use this card component whenever we want I can include four if I would like all right everybody so that is us making a card component in the next video I'll discuss props where each component can have different values because we don't want all of our components to look the same and that was some react practice by making a card component yo what's going on everybody so in today's video I'm going to show you a few ways in which we can style react components with CSS this topic doesn't include external Frameworks such as Tailwind or pre-processors such as SAS I'm going to cover a few of the more basic techniques including external modules and inline CSS styling we will need a component to work with let's begin with a button component let's go to our source folder new file button. jsx we'll create a function based comp component because we like function based components be sure to export it because I sometimes forget to do that so let's do it now export default the name of the component then we will return a single button element with text that says click me normally when setting a CSS class you use the keyword class however in jsx that's a reserved keyword we'll instead use class name with a capital N I'll set my class name to be button all right then we just need to import this button component going back to our app component that's the parent we will import button from its location SL button. jsx and now we have a button component to work with there's my button let's begin with external CSS styling we should already be a little familiar with it already heading to our index CSS stylesheet we can apply some Global Styles we will select the class name of button dot to select a class button let's apply the following CSS properties but feel free to make any changes or alterations I will begin with a background color I've already pre-picked a color personally I like using hsl values 200 for the Hue 100% for the saturation 50% for the lightness that will give you a light blue color for the font color that would be the color property I will set that to be white for padding let's say 10 pixels by 20 pixels border radius to round the corners I will set that to be five pixels border none to remove the Border then let's change our cursor to be a pointer when we hover over the button that's not a bad looking button I am zoomed in to like 300% just for this demonstration all right we have utilized an external CSS stylesheet they're easy to use for simple projects such as making a YouTube video tutorial it gives you flexibility with media queries and pseudo selectors you can use external stylesheets to apply Global Styles throughout your application however using external stylesheets can lead to naming conflicts especially when you have more components and classes to work with if you have a large web application you'll likely have all sorts of different buttons you would need a strong naming convention and good organization two buttons you may create might have the same class Name by mistake and with large applications it might be difficult to keep track of all the different class names moving on to Method two let's cut all of these properties save we're going to create a module now that's the second method we'll create a dedicated CSS stylesheet specifically for each component what you may see some developers do is they'll create a new folder specifically for their component let's create a new folder which we will name button the name of our component let's move our button component to the button folder let's move it be sure to update any Imports as well my app component is now importing the button component from the button directory within our button folder we'll create a new file this will be a CSS stylesheet which we will name the name of the component in this case button. module. CSS let's paste all of those properties that we cut before now from our button component we will need to import this module at the top we will import styles from the location of that module SL button. module. CSS for our class name we will use a set of curly braces to use a dynamic value our class name will equal our import of styles dot the name of the class button and there's our button again the thing about modules is that it avoids naming conflicts because a unique class is going to be generated for you via a hashing algorithm if I were to right click on this button and go to inspect this class name is unique it's generated via a hash so with modules we don't have to worry about naming conflicts modules are also convenient if each component has its own unique style however a few of the downsides though with using modules is that it does require additional setup and Global Style aren't applied easily you would have to import them from elsewhere and that's a whole thing let's remove our button component from the button directory let's put it back in source and delete our button directory going to our button component then remove the import as well we don't need that anymore now we're going to use inline Styles what you see some people do is they'll create a JavaScript object named styles Styles equals a set of curly braces for an object let's paste all of those CSS properties we're within jsx code right now we can't use any dashes we'll switch to a camel case naming convention all values Should Be Strings each property should be comma separated let's remove our class name we will set the style attribute to equal use a set of curly braces to insert a dynamic value we will insert our Styles object that contains all of these CSS properties and now we have done inline CSS styling inline CSS styling is convenient and easy easy to understand it prevents Global style conflicts because we're not working with class names it's great for isolated components with minimal styling such as a like button or a subscribe button however inline styling can be increasingly Less maintainable in large applications it reduces the readability of your components especially if you have a lot of CSS properties it's not great for any complex styling such as responsive CSS it tends to be better for components with minimal styling all right everybody so those those are three different ways in which we can style react components with CSS external which is great for Global Styles or small projects modules which is preferred for individual components that have their own unique Styles and inline which tends to be good for any small components with minimal styling use what's best for your project or your own personal preference or whatever your team prefers if you're working on a project together there's no one siiz fits-all approach unfortunately myself I prefer to use modules but throughout the series I'm going to be using a lot of external CSS just because our projects are really small and well everybody those are a few ways in which you can style react components with CSS hello everybody so today I got to explain props props short for properties they are readon properties that are shared between components a parent component can send data to a child component when you include a component within a parent you can send that that child component key value pairs in the last video we made cards but all of our cards were identical using props we can send a child component individual values so that they're all unique let's go over an example we're within our app component I will create a new component let's go to our source folder go to new file we will create a component for students to display student data student. jsx we need to create a function function student parenthesis curly braces then don't forget to export default the name of the component student in order for this component to accept props this function needs a props parameter props is going to be a JavaScript object so let's add our return statement we'll include a few HTML elements we'll start with a div within our div I will include a paragraph element within our paragraph We'll add the text Name colon space we'll include a set of curly braces to inject some JavaScript let's take our props this is an object access the name property however we still need to pass in a value for the key name so heading back to our app component we need to import the student component let's do so at the top import student from the location where the student file is found/ student. jsx let's include a student component within our app component student now if I would like to send some data to my student component student is going to be the child in this case app is the parent we'll need to list key value pairs the key will be name equals some value for the value associated with the name key let's say SpongeBob when I save and update everything we have the name SpongeBob when we send key value pairs to a component they're all stored within this props object to get the value associated with the key you type props dot the name of the key that will give you the associated value on my web page I'm going to zoom in a little bit just so you can see it that's good for now heading back to our app component let's send another key value pair let's send an age if you're going to store some data as a value if it's not a string literal you got to enclose it within curly braces let's say Spongebob his age is 30 we now have access to this age key heading back to our student component let's create a new paragraph age colon space to include some JavaScript we got to use a set of curly braces we are accessing the props object do access the key of age SpongeBob's age is 30 okay let's send is student is SpongeBob a student we'll create a key of is student equals add a set of cly braces is student will be a Boolean true or false SpongeBob is in boting school currently he is a student let's save heading back to our student component I'll include a new paragraph student colon space curly braces props do is student SpongeBob is a student that is true however our Boolean is not displaying so with a Boolean I recommend using the trary operator if is student within props is true then we'll return a string literal of yes otherwise we'll return a string literal of no let's update everything yes SpongeBob is a student you can place complex JavaScript code within your HTML code booleans don't display directly to the Dom you typically find them used within tary operators or some sort of conditional if some value is true return or do this if not do something else now if I were to pass in a Boolean value of false well that will change to no SpongeBob is not a student let's change that back to true now before I include a few more components I'm going to do a little bit of CSS styling just so that all of this is going to be more readable I'm going to zoom out to 100% where it was originally within my student component within the enclosing div element I will set a class name remember that with jsx you have to use class name not class because class is a reserved keyword let's name this class student then heading to our CSS stylesheet index.css feel free to clear out anything within here I will select the class of student I'll change the font family to be aiel I'll add a backup of s serif in case aiel can't display for some reason let's change the font size to 2 em for 200% I'll add a little bit of padding 10 pixels I'll add a border border one pixel solid pick a color I like hsl values I'll set the transparency down a little bit to like 80% let's go with like 50% lightness I'll remove any margin around the paragraph elements we are accessing the class student then access any paragraph elements margin zero okay that's not too bad so this is a student component to display some student data we'll reuse the student component but pass in different data each time we'll create a new student component this Student's name will be Patrick Patrick's age Patrick will be 42 is Patrick a student is student I will set that to be false let's update our web application and there is Patrick's data name Patrick age 42 student no let's add a few more student name equals Squidward Squidward's age will be 50 is student Squidward will not be a student that will be false then let's add Sandy she'll be the last student student name equals Sandy sy's age will be 27 is Sandy a student she will be that will be true there we are all right we have created four student components each has different values depending on what we pass into props we're going to move on to prop types prop types prop types are a mechanism that ensures that the past value is of the correct data type for example within props we have an age we would like to ensure that the age value passed in is a number not a string or a Boolean if it isn't then react can emit a warning within our console mostly for debugging purposes if you're working with props it is good practice to also use prop types so here's how to create prop types after our student function we'll type the name of the component student. prop types equals curly braces now we do have to import prop types it's found within the node modules folder where is it this should be an alphabetical order there it is prop types at the top of our jsx file we will import prop types from prop types prop-types within our prop types I would like to ensure that any name passed in is going to be a string if it's not we'll issue a warning within our console Name colon space prop types. string let's do this with age age will be a number age colon space prop types. number then is student is student will be a Boolean is student colon space prop types dob for Boolean all right and those are our prop types heading back to our app component for SpongeBob's age if I don't pass in a number let's say I pass in a string a string of 30 well this won't prevent the program from running but it will issue a warning within our console if we rightclick go to inspect go to console we can see a warning failed prop type invalid prop age of type string supplied to student expected number and here's a location so this is good for debugging it won't stop the application from running just issue a warning it is good practice ice to include prop types if you're accepting props then lastly we're going to discuss default props default props are default values for props in case they are not passed from the parent component let's say we create a new student component but we don't pass in a name we can add a default value such as guest just in case that value isn't passed in one way or another okay let's add default props down here student. default props equals set of curly braces for the name the default value will be guest age will be zero is student will be false to test this let's go to our app component we'll create a new student component but don't pass in any props we'll create an empty student component with no props that appears to work the name is guessed the age is zero student is set to know so if I were to include a name let's say name equals Larry well Larry's name is going to be set we didn't include any key value pairs for age or is student we ended up using the default values zero and no all right everybody so those are props they are readon properties that are shared between components a parent component can send data to a child component when you include a component you can send that component key value pairs which allows you to reuse that component but have unique data and those are props with react hey sup everybody in today's video I'm going to give you an introduction to conditional rendering in react conditional rendering allows you to control what gets rendered in your application based on certain conditions by utilizing conditional rendering we can show hide or change components here's an example we'll create a user greeting component let's go to our source folder new file user greeting and this will be a jsx file I will be using function based components function the name of the component user greeting we will have one parameter props we learned about props in the last video before I forget I'm going to export default the component name just so that we can import it later heading back to our app component we will return a user greeing component user greeting by using props we'll send two key value pairs to our user greeing component is logged in this will be a Boolean value we'll check to see if we're logged in or not and a username username equals this is a string so we do not need a placeholder type in your name or username then we do need to import user greeting import user greeting from a location. slash user greeting. jsx let's save everything head to our user greeting component we have these two key value pairs that are stored within our props object I'll use an if statement to check to see if we're logged in or not if props is an object we will access props followed by dot is logged in is this true or not not if it is then let's return an H2 element with text of Welcome I'd like to include some JavaScript I'll use curly braces let's take props dot our username let's see if this works welcome bro code or whatever your name is so what if we're not logged in I will set is logged in to be false well nothing appears to happen going back to our user greeting let's add an else statement else we will return an H2 element with text of please log in to continue please log in to continue within our function based component we can check some logic using an if statement if some condition is true return this if not return something else now Technic technically you don't need the else statement you could just say return because when you return you exit this would work too as you can see I don't think it's as explicit as using an lse statement another option is to use the tary operator which we learned in JavaScript we will return check props do is logged in add a question mark is this true or is it false if it's true then we'll return an H2 element that says welcome I'll add some JavaScript props do username I'm going to close this menu just so we can see if this condition is true return this otherwise add a colon we'll return something else we'll add an H2 element please log into continue this statement is pretty lengthy I'm going to put each part of the statement on a new line just so we can read it easily if is logged in is true return this H2 element if not return this H2 element currently we're logged in that is true if I set this to be false well then we get that login prompt please log in to continue you'll more commonly see people use tary operators rather than IFL statements just because they're more concise let's apply some CSS styling going back to our app component we'll set is logged in to be true We'll add a class name to each of these H2 components class name equals the first H2 element if our condition is true we'll have a class name of Welcome Dash message our second H2 element will have a class name of login D prompt going to our CSS stylesheet let's select the class of Welcome message I'll apply the following CSS properties let's set the font size to be 2.5 em I'll change the background color I like using hsl values I'll go with this shade of green let's change the font color to be white I'll add a little bit of padding 10 pixels I'll add a border radius around the corners then set margin to be zero here is our user greeting component if the user is logged in let's style the login prompt class next do login prompt really I'll just copy these properties but we'll change the background color let's change the background color to be red all right let's set is logged in to be false then our user greeing component should have those different CSS properties please log in to continue if I set that to be true well then we're logged in welcome your username within our user greeting this tary operator is very verbose here's another way in which we can use the tary operator in this situation let's create two constants const the first will be welcome message be sure not to include any dashes though separately we'll store these H2 elements I'm getting a copy of this first H2 element we'll store that within our welcome message just so we can read it I'm going to place each line on a new line then let's create another constant const login prompt be sure to eliminate any dashes we will be using a camel case naming convention take our second H2 cut it paste it and there we go I find that a lot easier to read so we're going to take our condition is logged in if that's true we'll return our constant our welcome message otherwise we'll return our other constant our login prompt and that will work still the same let's set that to be false please log to continue set it back to be true welcome your username I find this syntax a lot easier to read now it is good practice if you're accepting props to set up prop types just in case the values that are passed in are not of the correct data type you'll at least get a warning for debugging purposes it's a good habit that we should develop we learned about prop types in the last video so at the top let's import prop types from prop-types after our function take our user greeing component do propop types equals take our keys is logged in the value with this Associated key should be a Boolean prop that's capital T types dob then a string for username user name prop types. string all right the last thing we're going to do is set up default props what if somebody's logged in but they don't have a username we'll set a default for the username as guest so after our prop types we'll set up some default props again take user greeting that's the name of our component. default props equals is logged in will be false and username will be G if there's no username passed in all right going back to our app component if a user is logged in but there's no username let's eliminate that we'll get the welcome message of Welcome guest now if a user is not logged in regardless we don't display the username all right everybody so that's conditional rendering you can check some sort of condition based on if that condition is true or false we can show hide or change components there's many different ways in which you can do that and well everybody that is an introduction to conditional rendering in react hey everybody I have a huge video for you today today we're going to talk about rendering lists in reactjs this can be pretty complex we'll go through it step by step what we'll do in this tutorial is create a new component to hold our list let's go to our source folder create a new file I'll name this component list this will be a Js x file to finish creating this component this will be a function based component with the name of list then be sure to export it export default list we'll start with something very simple we'll create an array of fruit this will be const fruits equals think of some fruit for me I'll pick an apple Orange banana coconut and a pineapple let me show you what would happen if we were to return our array within our list component we will return our array of fruits but we will need to import it going back to the app component we will import our list component import list from a location . SL list. jsx we need a return statement to be sure you have one we will return a list component and here is our list let me zoom in it's all one big string Apple orange banana coconut pineapple heading back to our list component we need to convert our array of strings into an array of list item elements we can use the built-in map method to do that we'll create a new array of list items the map method is going to return a new array after running it through a function const list items equals take our original array a fruits use the built-in map method then we'll either pass in a callback a function expression or an arrow function we'll use Arrow functions because I like Arrow functions for every fruit in fruits Arrow meaning do this we'll create a new list item element that has the text of our fruit the array item we're not going to return our fruits array we're going to return an unordered list we're going to insert some JavaScript with curly braces will include our list items it's an array of list items and here's our array whoops but I forgot to enclose fruit with curly braces my mistake they much better or if you prefer we can turn this unordered list into an ordered list with a pair of O tags o there they're all numbered that's how to render a simple array if you're working with an array of strings and you'd like to sort this array beforehand you can use the sort method fruit do sort the sort method will sort an array in place however this doesn't work with numbers because we're sorting lexico graphically we would treat numbers and symbols as characters more on that later let's go over example two we'll convert our array of strings into an array of objects each object will have a name property and calories calories per serving so let's enclose all of our elements within a set of curly braces to make them objects I'm going to place each of these objects on a new line just so that I can read it more easily each of these objects will have a name property the name property will be set to the original string for our array the first object will have a name of Apple let's add calories too calories per serving I did a quick Google search of some the calories per serving for these fruits I don't know how accurate these are but they seemed right our first object has a name of Apple calories is set to 95 name orange calories 45 name banana calories 105 name coconut coconut calories 159 name pineapple calories 37 all right we now have an array of objects there's a few changes we're going to make if I run this again our list isn't rendering I need to display the name property of each fruit fruit. name property we have one issue behind the scenes I'm going to right click go to inspect then go to console warning each child in a list should have a unique key prop react wants us to assign a key to each list item each key should be unique in my array of objects each fruit has a unique name I could use that we will set the key attribute to equal include some JavaScript fruit. name that warning should go away which it did if there's a possibility that two objects can share the same name you'll want to use some sort of unique ID in a real world scenario if you're pulling data from a database each row of data is going to have some sort of unique ID so we're going to mimic that let's add a new property for id id will be one for Apple these will be in ascending order orange will have an ID of two banana is three coconut is four pineapple is five we'll set the key to be each ID this would be much better than using the name you can have a naming conflict if two objects share the same name like if these were people you could have two people named Bob that warning should be gone which it is react would like a unique key for each item just so it can more easily keep track of items being inserted and removed along with each element I'm going to display the calories next to each element so we'll make a few changes I'm going to put these HTML elements on a new line for readability after the fruit's name I'm going to add a colon a non-breaking space character and Pand nbsp for space oh then not a semicolon forgot about that then we'll insert some JavaScript fruit. calories for the calories of each fruit I'll make it bold I'll enclose our calories with a pair of bold tags which is just B now we're going to sort the items in our list we'll do that before the map method I'm going to sort our array of objects by their name property we'll take fruits use the sort method the sort method will sort an array in place we'll write a custom sorting function we have two parameters A and B A for the first item B for the second then we iterate over the entire array we need an arrow meaning do something to lexicographically sort string properties within an array we can use the following method we'll take the name property of a use the built-in local or local some people say compare method I misspelled that yeah I can't spell compare to b.n name that should sort our aray of objects by their name property for reverse order let me turn this line into a comment this is alphabetical for reverse alphabetical order we just have to replace a with B and B with a there pineapple orange coconut banana apple with apple being at the bottom let's sort by calories fruits. sort this one's easier again we have our parameters a comma B Arrow the calories of a a. calories minus b. calories that one's easy we have pineapple at the top followed by orange apple banana coconut this is in numeric order for reverse numeric order reverse numeric or descending you could say the calories of B minus the calories of a now we have coconut at the top with pineapple at the bottom with the least amount of calories in this next section I'm going to demonstrate to you how we can filter objects by a certain criteria we'll filter anything that's greater than 100 calories we'll create a new array of fruit that has low calories we'll create a new array const low cal fruit equals take our original array of fruits use the built-in fil method we'll have one parameter of fruit examine each fruit in our array of fruits Arrow then a condition here's the criteria check the calories property of our fruit if it's less than 100 filter it and add it to a new array instead of displaying our array of fruits let's display our new array of low calorie fruit oh that should be plural local fruits when we create our array of list items replace fruits with local fruits and any instance of fruit with lcal fruit singular so we have three instances of fruit let's replace those let me clean this up a little feel free to pause the video if you need to write this down we have three fruits that are low calories the calories is less than 100 let's find any high calorie fruits we can just copy this line of code paste it but change the condition examine the calories of each fruit filter it out if the calories are greater than or equal to 100 the name of this array will be high Cal fruits replace low cal fruits with high Cal fruits replace low cal fruit with high Cal fruit singular and do that for the other instances as well there we are we have two fruits that are high in calories bananas and coconuts that is US using the filter method to filter out list items let's replace High Cal fruits with fruits high Cal fruit with fruit to display our original array for the next part of this lesson we're going to transform this list component so it's reusable with different lists currently the way that we set this up is that each list component that we create has its own list of fruit so we're going to make some changes let's cut our list of fruits going to the parent component of app we'll paste our list of fruits then pass it as props to our list component with our list component we will have a key of items equals insert some JavaScript our list of fruits let's also add a category key category equals for my category let's say fruits eventually we'll add an H3 heading we're now going to send all of this data to the list component but we have to set up props with in the list function we have a parameter of props we'll access the items of props to get our fruit we'll create const item list equals not to be confused with list items list items is what we get after we map it item list equals props do items and remember that items is our fruits array replace fruits with item list replace fruit with item do that here here and here there's our list again if you're going to sort or use the filter method be sure it's item list not fruits because now list is a reusable component I'll add our Category 2 that's stored within props const category equals props do category currently we're returning a single ordered list I'll also include an H3 element include some JavaScript we need curly braces add our category however with our return statement we can only return a single element or many elements that are wrapped within a fragment let's create a fragment that will enclose all of our markup there we are going back to our app component let's create a new list just to make sure that our list component is reusable let's copy our array of fruits paste it we'll create an array of vegetables the IDS will be 6 7 8 9 10 the name of my first item will be potatoes calories 110 per serving celery calories will be 15 carrots calories 25 corn calories 63 broccoli calories 50 now we should be able to create a new list component within our return statement we're going to need a fragment again we'll return a second list item component the items will be vegetables the category will be a string of vegetables Bo boom there we go here's our second list component so our list component is now reusable we can pass in many different types of lists to make this look better let's apply some CSS styling we'll have to set a class name first our H3 element will have a class name equal to list- category our ordered list will have a class name of list items all right going to our CSS stylesheet index.css let's work on our list category first use dot to select a class list category I'm just going to run through these real quick I'm going to make sure I'm zoomed in to 100 because I was zoomed in beforehand font size 2.5 em font weight will be gold pick a color I'm going to stick with hsl values I'll set the lightness to be 20% I'll add a little bit of margin on the bottom 10 pixels text align Center I'll add a border three pixel solid I'll add a border radius to round the corners and a background color pick a color again I'll use hsl this one I pre-picked already 185 100% 50% % that's not a bad looking color pick whatever color you would like let's work on our list item elements we need to select the class of list items do list items select each list item within this class I'll increase the font size to be 2 em I'll remove the list style but you don't have to list Style will be none pick a color again I'm using hsl values I'll set the lightness to be 25% text align Center and margin will be zero all right now when I hover over one of these list items I'll apply a hover effect take our class list items take each list item access the hover sudo class I'll change the brightness the color will be something a little bit brighter I'll set the lightness to be 45% and then the cursor will be a pointer yeah not bad that's how we can apply some CSS styling to list components all right heading back to our app component what if we have an empty list for example with our fruits I'm going to cut it we can use conditional rendering to render our list only if there's elements let's put those back we're going to write some JavaScript we need some curly braces let's take our array of fruits access the length property is it greater than zero question mark if it is we'll return our list component colon if it's false we can return null let's do that with our vegetables too take our array of vegetables access the length property is it greater than zero tary operator if it is return our list component if not we can return null if one of these lists doesn't have any elements we won't render that component there is a short hand to the tary operator we don't need to write or else return null what we'll use instead of the tary operator is the and logical operator we can effectively shortcircuit the first expression then we don't need colon null it's a little less code our list component will always be true because it exists however the first expression might not be so if this condition is false we don't render this if it is true we will render this let's try that again let's remove these elements we don't display the fruits list component and we will not display the vegetable list component this is known as short circuiting one thing to consider what if our category is missing let's remove our category from fruits well I would like to add some sort of placeholder here or what if one of these arrays was missing well nothing displays not even vegetables we should add some default props in case one of these properties is missing so going back to our list component before we export it let's set up some default props take our component name list. default props equals within a set of curly braces let's set our category category property to be category as a placeholder if for some reason these components don't have a category We'll add a placeholder of category which at least looks better if we're missing an array that's a bigger problem let me go to inspect then console we're trying to map something that's undefined we have no array to work with so nothing is rendering so as a backup within default props let's set our items to be an empty array items will be an empty array if one of these arrays was missing for some reason at least the category is displayed as well as the subsequent components at least something will display okay then lastly as good practice if we're accepting props we should set up prop types I'll walk you through it if you're just joining us with prop types if the incorrect data type is passed into props when we debug it'll give us a warning to use prop types we have to import it at the top of our list component we will import prop types from prop types take our component of list list. prop types equals set of curly braces for our category this will be a string category colon space prop types. string add a comma for another line okay this is where it's going to get tricky we have an array of objects we'll access the items property items colon space prop types I'm going to move down a little bit dot we have an array array of we have an array of objects prop types. shape method we have to define the shape of each object object each object is going to have its own data types we have a number string then number we're defining an object we need a set of curly braces ID colon prop types do number comma for another property I'll put the next one on a new line for readability we have a name property which will be a string prop types. string then calories prop types. number and that's it let's head back to our app component our prop types should raise a warning if some of our data is of the wrong data type for example let's say that calories is now the string Apple maybe somebody mistyped it twice you can see that right here it changed let's go to inspect console and here's our warning because we have prop type set up invalid prop items index zero calories of type string if we didn't have prop type setup we wouldn't receive that warning this may go unnoticed it is good practice if you're accepting props to also set up prop types it's a little more complicated if you have an array of objects but here are the steps all right everybody I know this was a massive topic thank you all for watching feel free to take some time to study and work with this before moving on to the next topic if you would like we did Cover a lot of material and well those are various ways in which we can render lists in react hey uh so today I'm going to explain click events and how to handle them in react a click event is an interaction when a user clicks on a specific element we can respond to clicks by passing a call back to the onclick event handler in this example we'll create a button let's create a button component go to new file button. jsx we will use a function base component function button then be sure to export it export default button going back to our parent component of app we will need to import our button import button from its location button. jsx then we will create one button component going to our button component we will return a single button element the button will have text of Click me hey for fun I'm just going to add it an emoji but you don't have to and I will zoom in so you can see it many HTML elements have an onclick event handler we can set the SQL to a JavaScript callback but we need a function to work with So within our button function we can write an inner function const handle click I will assign this equal to either a function expression or an arrow function I like Arrow functions so I'm going to stick with an arrow function when we click on the button what do we want to do let's console.log the word ouch so we have our function we will set the onclick event handler equal to a callback a call back to this function when we click on the button do this if I went to my console inspect console Let me refresh this if I click on the button we execute this code we will output the word ouch every time I click the button if your function has parameters there's one change we'll need to make let's create a second function const handle Click 2 this function will have a parameter of name we'll use an arrow function we will console.log I'll use a template string let's display the name stop clicking me for the onclick event handler we will set a call back of handle click to but we have parameters that means we need to send a matching number of arguments I will send my first name but feel free to use your name I didn't click on the button yet I'm going to go to inspect console uh Let me refresh all this I didn't click on the button yet but we've already called that function if you add a set of parentheses after a call back you'll invoke it right away so we don't want to do that if we have arguments we need to send to a function we could wrap this call back within a function expression or an arrow function let's use an arrow function when we click on the button do this that will prevent us from calling this function right away so let's refresh everything then when I click on the button then we execute this code bro stop clicking me bro stop clicking me bro stop clicking me so that's how to send arguments to a function now in this next example We'll add some conditions let's set the onclick attribute to be a call back to handle click if you have more than one line of code for your arrow function you'll need to use a set of curly braces let's add a count variable let count equal Z with our handle click function let's have one parameter a name what would we like to do let's check to see if our count variable is less than three if it is let's increase count by one then console.log I'll use a template string let's add our name parameter you clicked me add a placeholder count time or times else if the user clicked me more than three times let's console. log a different message let's say add a placeholder name stop clicking me with the onclick event Handler we have a parameter that means we have to wrap this call back within a function expression or an arrow function let's use an arrow function for Simplicity we'll pass in a first name pass in your own first name so let's save and refresh everything go to inspect console when I click on the button once it's going to display bro you clicked me one time bro you clicked me two times bro you clicked me three times after the third time we'll display a different message bro stop clicking me bro stop clicking me bro stop clicking Me So within your functions you can write some conditions now I need to explain the event parameter let's recreate that handle click function const handle click equals with click events were automatically provided with an event argument it's an object that describes the event that occurred but as a parameter people usually shorten the event parameter to be simply e let's print our event console.log e our event we'll need to set the onclick event handler we have one parameter so we need to wrap this within an arrow function handle click for the arrow function we'll have e for the parameter and E for an argument for the handle click function let's click on the button we're now outputting the event its type is synthetic base event and it has all of these properties and methods such as where you clicked on the screen there's a timestamp and a Target by utilizing this event object that gives us many different possibilities for this demonstration let's change the text content of the button so there should be a Target property here I am going to change the text content that should be a property yep there it is so what we'll do after clicking on the button we will access that event object follow this with DOT that's the property accessor we're selecting the inner target object then selecting the text content property let's set that equal to be ouch so now when you click on the button the text of the button should change to ouch I'm going to add an emoji too there we go okay let's try this again this will be fun click me ouch there's also the on doubleclick event handler instead of onclick you'll say say on double click so when we click on the button once now nothing happens but once I double click that's when we'll execute this function now I'm going to double click ouch if you need to handle a double click you just have to use the on double click event handler all right let's move on from using a button this time let's use an image in my assets folder I do have my profile picture from my YouTube channel find a profile picture of yourself or a picture you like we're going to create a new component let's go to our source folder I will name this component profile picture. jsx we will create a function with the name of profile picture then be sure to export it export default profile picture then going back back to our app component we will import our profile picture component from its location profile picture. jsx let's include our profile picture component instead of our button all right so within our profile picture component I will store a URL within a constant constant image URL I will list a relative file path so my image is within my assets folder my file location but it might be different for you mine is going to be SL Source SL assets slash the name of the image including the extension mine is profile. jpeg we will return an image on lint I AMG for an image element I will set the source equal to some JavaScript I need to set a curly braces I will set it equal to my image URL and let's see if that worked yes it did but I'm going to zoom out to like 150 my image is small let's add a handle click function const handle click equals an arrow function to test it let's console.log the word ouch then we'll need to set the onclick event handler within our image on click equals a callback to handle click so let's save and refresh everything let's go to inspect console when you click on your image it should display the word ouch every time you click it let's utilize the event object that's generated we have one parameter e for our event that means we'll have to change the call back to Be an Arrow function e for the parameter Arrow handle click we have one argument of e so what should we do now when we click on the image let's hide the image we'll need to access that event object access the target object that's found within access its style then the display property we will set the display to be none when we click on it so then if you were to click on your image it should disappear so by accessing the event object that gives us a load of different possibilities for what we can do all right everybody so that is an introduction to handling click events in react a click event is an interaction when a user clicks on a specific element we can respond to clicks by passing a call back to the onclick event handler and well everybody that is an introduction to click events in react hey what's going on everybody in today's video I'm going to explain the usate react hook and near the end of this video we're going to create a reactive counter program so sit back relax and enjoy the show I haven't explained what react hooks are yet a react Hook is a special function that allows functional components to use react features without writing class components this was a change made in react version 16.8 basically we no longer need to write class components we can write function-based components that use react hooks to use react features there are many react hooks if a function begins with use it's probably a react hook use State use effect use context use reducer use callback and more UST state is the most widely used UST state is a react hook that allows the the creation of a stateful variable and a Setter function to update its value in the virtual Dom basically by using the usate hook we can create not just a variable but a stateful variable when you update this variable that change will be reflected in the virtual domum normal variables don't when you use the UST State hook you're given a variable and a Setter function specifically for that variable so what we'll do in this example is create a new component going to our source folder we're going to create a new file we'll name this component my component we use react hooks in function based components so make sure you're not writing a class component with this component we will export it export default my component then be sure to import this because I'm probably going to forget if we don't do it now so we will import my component from its location slash my component and this is a jsx file let's return one my component and we are ready to begin in order to use a react hook we need to import it at the top of this component we will import the react Library however we don't need the entire react Library we can use object destructuring to extract individual variables or functions I would just like the UST State function we don't need the entire react library from its location react we now have access to this UST State function using the UST State function we'll create a stateful variable and a Setter function to update that variable so let's declare const we're going to use a set of straight brackets for array destructuring equals use State function the use State function returns an array with two ele elements a variable and a Setter function we're going to use array destructuring to destructure these two elements we'll create a stateful variable for name then we're given a Setter function specifically for this variable a common naming convention is to type set than the variable name with camel case naming convention and that's it if we ever need to change the value of the stateful variable we have to do so with this Setter it's a function at the bottom we're going to return return a div element within this div element we'll create a paragraph element and a button we'll begin with a paragraph element that has text of name and I'm going to zoom in a little bit I will insert some JavaScript using curly braces let's display our name following our paragraph element let's include a button the button will have an onclick attribute equal to a JavaScript function so we need a set of curly braces to embed that let's create a function to update name for the text of the button let's say set name all right now we just need to declare this function I'll use an arrow function const update name equals Arrow function so what would we like to do okay let's attempt to set our name equal to type your name or some other name I'm just going to type in SpongeBob if I click on this button we should update our name right well that doesn't appear to work so if I were to console.log my name variable then attempt to update it using this button if I were to go to my console hold on I'm going to use let so we can update it if I attempt to change this name of the variable it does so within our console but it doesn't update in react the virtual Dom is still displaying the previous state so if I would like to display any changes I will want to use that Setter instead of setting our name equal to a new value I'm going to change this back to be a constant we will use the setter function and pass in a new value so let me type in a new value and that should work we have updated our name when you use the setter function of a stateful variable it will trigger a render of the virtual Dom normal variables don't that's why the UST State react Hook is useful we can create a stateful variable when the stateful variable gets updated with its Setter function it triggers a rerender of the virtual Dom with the usate function you can pass in an initial state currently we're not passing in anything for the initial state State I will set this to be guested when I refresh everything and start over the initial state is guessed whatever value you pass in to the UST State hook then I can set my name again to something else now we're going to create an age variable and increment it const we're going to use array to structuring we need a stateful variable like age and a Setter function for that age set age equals use state if you would like an initial value you can place that within the UST State function I'll set the initial value of AG to be zero I'm going to copy this paragraph and this button change name to be age we'll create a function to increment age the text on the button will be increment age now we just need this function const increment age I'll use an arrow function to increment our age we will use the set age function let's take our age + one so our initial value for our age is zero but every time I click on the button we will update the value of that variable so every time I click the button button we're increasing our age by one or even a different number this time I'll increase our age by two on each button click so we start at zero then we'll increment by two 2 4 6 8 10 now this time we'll create a Boolean variable and toggle it between being true and false using the US state hook we will create const is employed the setter function will be set is employed equals the use State hook I would like an initial value a false let's create a paragraph element and a button I will set the text of the paragraph to be is employed instead of displaying a Boolean directly let's use the tary operator for conditional rendering is employed if that is true will display yes otherwise no when we click on the button let's create a function to toggle toggle employed status that's kind of a Long Function name all right let's create a function const toggle employed status equals an arrow function we will use the setter function set is employed pass in a new value let's switch this value from being false to true and true to false every time we click the button since this is a Boolean we can use the not logical operator to reverse it so let's say not is employed and let's see if this works is employed no oh let's change the text on the button too toggle status there we go all right when we click on the button we can toggle this Boolean from being true to false and false to true and this should happen every time I click the button as a project what we're going to do now is create a counter program so let's close out of my component we'll create a new component for a counter component counter. jsx this will be a function base component function counter then be sure to export it export default counter going back to our app component we will import our counter component from its location counter. jsx then we will include one counter component and that's it in order for us to use the US state hook we have to import it from the react Library import react we'll use object destructuring just to get the UST State hook and nothing else from its location of react all we need is one variable a counter let's say const we'll use array destructuring create a stateful variable of count and a Setter function for that count set count equals the use State hook would we like an initial value for count we would like the initial value to be zero we'll create a few functions to increment decrement and reset the counter const increment equals I'll use an arrow function to update the count to increment it we will use the set count function the value we'll pass in is Count + one then let's do this for decrement const decrement count minus one then reset const reset for set count we'll pass in zero to reset the count now we're going to return some elements we'll also style this with CSS let's begin with the div element I'm going to scroll down a little bit my div element will have a class name name equal to counter- container I will create a paragraph element with a class name equal to count display to display the number for the text of the paragraph I will insert some JavaScript and display our count variable we'll create three buttons for the first we'll create a button element this button will have a class name of counter- button the onclick attribute will be set equal to a JavaScript function this first button will be the decrement button for the unclick attribute we will set this equal to the decrement function for the text on the button we'll say decrement and there's our first button so let's copy this button paste it the second button will be for reset the text will be reset then the third button will be increment onclick will be the increment function the text will be increment all right and that's all that we need let's check it for functionality to be sure that everything works we can increment this number we can decrement it and we can reset it so for the icing on the cake let's style it with CSS going to our index CSS stylesheet we'll apply the following CSS let's select our counter container do counter container I will text align Center change the font family I will pick a s serif font of Arial with a backup of s serif next we'll select the count display select the class of count display that would be this number will increase the font size to something massive like 10 em RM works too oh okay that's a little too big but I am zoomed in actually you know what that's perfect I will set the margin top to be zero to close this Gap and I will set the margin on the bottom to be 50 pixels then let's work on the counter buttons next select the class of counter button I will set the width to be 150 pixels the height to be 50 pixels the font size to be 1.5 em I will set the font weight to be bold set the margin to be 0 pixels by 5 pixels this would be for the left and right of the buttons change the background color pick a color that you like I'm going to use hsl values though that's pretty good I will set the color of the font to be white remove the border border none set the Border radius to round the corners five pixels and change our cursor to be a pointer if we hover over the button when we hover over the button I'm going to change the background color of the button so with the counter button class with the counter button class we will select the hover sudo class we'll take our background color decrease the lightness to be 10% darker there we are and that is all the CSS styling that we need we have our counter program we can increment the counter we can decrement it and we can reset it all right everybody so that is the US state react hook it allows the creation of a stateful variable and a Setter function to update its value in the virtual Dom when you include the UST State hook you're given an array of two elements we use array destructuring to create a stateful variable and a Setter function to update that variable and well everybody that is the UST State hook in react yo yo yo yo yo what's going on people so today I got to explain the onchange event handler in react onchange is an event handler used primarily with form elements including but not limited lied to input text area select and radio buttons onchange triggers a function every time the value of the input changes so let me give you an example we will be using the UST State hook so we need to import it import react I would like the use State Hook from react using the use State hook we're going to create a name variable a stateful variable const name and we need a Setter function for this variable set name equals the use State hook you can set an initial value I'll set mine to be an empty string I will be returning a div element to enclose all of our markup within my div element I will create an input element and here's my input element I will set the value of the input element to be some JavaScript my stateful name variable then I will set the onchange event handler to be a reference to a JavaScript function which we still need to create this will be a call back let's create a function to handle a name change it's going to be similar to handle click function handle name change we have one parameter an event that's going to be provided to us when we change the value of this input element I will invoke our set name function we will set our name variable to be access our event object access its Target then get the value property onchange is going to be set equal to a call back to this function when we type something or somehow change the value within here call the this function and then afterwards I will include a paragraph element that has the text of name and include some JavaScript I will include my name variable so what should happen is when I type in a name it will update in real time with use State I can set the initial value to be something too I'll set my initial value to be guested the onchange event handler triggers a function every time the value of the input changes right now we have an initial value if I start deleting this my name is going to update this time we'll create an input element for a number instead of text I will create a stateful variable for a quantity as if we're ordering something quantity and we need a Setter function set quantity equals the use State hook would we like an initial value not yet but we'll get to that later I will create a function to handle quantity change it's the same formula as before we will be provided with an event so let's write a parameter for that we will use the setter function for the quantity set quantity we'll pass in Access our event access its Target then access its value then we need some HTML elements let me scroll down I will create an input element I will set the value of this element to be our quantity then I will set the onchange event handler to be a call back to a job JavaScript function handle quantity change I will set the type of this element to be a number type equals number afterwards I will add a paragraph with our quantity and display our quantity variable so now we have arrows to select a number I will update the quantity to be one two 3 4 five I'll set an initial value of one let's pretend that we're ordering something we're going to assume that the user wants to buy at least one of something that's how you can use onchange to reflect a number that's changing within an input element all right now we're going to create a text area a user is going to be buying something we'll have a user leave a comment I will create const comment set comment equals use State I'll set the initial state of my comment to be an empty string then I'll create a function to handle comment change function handle comment change we have one parameter and event we will use our Setter for our comment then pass in Access our event access its Target then access its value then we need our HTML elements we will create a text area element I will set the value to be our comment variable then set the onchange event handler to be a call back to handle comment change I'm also going to add a placeholder for some placeholder text placeholder equals in my specific example this text area will be for specific delivery instructions if somebody's shopping on your site and they order something they might want to provide additional delivery instructions leave package on the back porch ring the doorbell after the delivery is complete stuff like that so for my placeholder I'll type in enter delivery instructions and there's my placeholder text then just to see if this updates I'll add a paragraph element with my comment then insert my comment variable all right let's see if this works leave package on front porch and avoid the killer Chihuahua that's how we can use onchange with a text area all right the next one's going to be a little more complicated we're going to use a select element for a drop- down menu we'll create a drop- down menu for a payment is somebody going to pay with a Visa a MasterCard a gift card const payment set payment this will be a payment type we'll use use State I will set the initial value to be an empty string then we need a Handler function function handle payment change we have one parameter and event then we'll use that Setter function for the payment set payment event access its Target then the value our select element has as a pair of tags we'll Place option elements within our select element the opening select element is going to have a value equal to our payment variable I will set the onchange event handler equal to a call back to the handle payment change function we have some options within our select element the text on my first stop option will be select an option so now my drop- down menu has select an option for this option's value I will set it to be an empty string this will be the default let's create another option the text on this option element will be a Visa if somebody's paying with a Visa card the value will be a string of Visa besides the defaults we do have an option for Visa then MasterCard Master Card the value will be a string of MasterCard and then a gift card gift card the value will be gift card so besides our default we have Visa MasterCard and gift card after our select element I'll create a paragraph the text on the paragraph will be payment then I'll display our payment stateful variable when I select Visa our payment is going to update with Visa Mastercard and gift card with use State I can even set an initial value I could set the initial value to be for example Visa Master Card or a gift card but I'll keep it as an empty string so we get that default text of Select an option the last form element I'll cover is radio buttons and these are going to be the most complicated we'll create a pair of two radio buttons for a delivery method either pickup or a delivery does somebody want to come into a store to pick up our package or is a driver going to take it to their residence I will create comp let's say shipping for the shipping method and a Setter function for set shipping equals use State for the time being I will set the initial state to be an empty string we'll create a Handler function function handle shipping change we have one parameter of event I will use that Setter function of set shipping access our event argument access its Target access its value within our HTML markup we're going to create a pair of radio buttons we'll create a label we need a pair of label elements the text on the first label will be pickup are we going to pick up our package from a store we'll create a second label I'll just copy what we have paste it the second label will be for a delivery within my label I'll create an input element I will set the type to equal radio I will set the value of this radio button to be pickup I'll place the these additional properties on a new line just for readability I will set the checked attribute equal to a JavaScript expression let's check to see if our shipping stateful variable is strictly equal to our value of pickup this will evaluate to be true or false if this expression is true then we'll trigger our onchange vent Handler and set it equal to a JavaScript function it's going to be a call back to handle shipping change let's copy this input element then within our second label paste it but we'll change our value to be pick up to delivery within our checked property check to see if shipping is strictly equal to delivery if this expression is true then checked will be true through this will trigger the onchange event handler just to reflect the change I'm going to add a paragraph element with text of shipping I will insert some JavaScript I will insert our shipping stateful variable I'm going to add a break after our first label just for readability I think that looks better if I were to select pickup the shipping method changes to pickup we're going to pick up our delivery from a nearby store if I change it to delivery the shipping method changes to delivery with the US state hook we can set an initial State let's assume that if somebody is ordering something from our site they will want it delivered I will set the initial state to be delivery and that did update but if somebody does want to pick it up they can easily just change that by selecting this radio button all right everybody so that is the onchange event handler it's used primarily with form elements including but not limited to input text area select and radio buttons onchange triggers a function every time the value of the input changes so for example if I were to type in my name into this input element that change is immediately going to be reflected in real time and well everybody that is the onchange vent Handler in react hey what's going on everybody in today video we're going to create a Color Picker program using react this serves as more of an exercise now that we know how the UST State Hook and the onchange event handlers work so let's get started all right let's begin everybody within our source folder we'll create a new file for a Color Picker component this will be a jsx file we will use function based components function Color Picker there are no parameters then let's be sure to export this export default Color Picker we need to return something for the time being I'm going to return a fragment just so that everything works going back to our app component we will import our Color Picker component from its location SLC colorpicker djsx then let's include one Color Picker component and that is all we need with the app component heading to the Color Picker component we will need to import the UST State hook import from react we'll use object destructuring just to get the UST State Hook from react within our Color Picker function at the top we'll use the UST State hook to create a stateful color variable const we're going to use array D structuring and create a color and a Setter function for that color we will use the use State hook for the color if you would like to set an initial color you can do that I recommend using hexadecimal values to keep it simple for example if you would like white that would be 6fs personally I'm a fan of using hsl values for Hue saturation and lightness but that can get kind of complicated you would need to pass in a JavaScript object with those three properties we stick with heximal values just to keep it simple then we'll create our HTML elements So within the return statement I will create a div element this div element will have a class name of Color Picker container with react when using CSS I like to use a hyphenated naming convention this development will contain everything we need for our Color Picker component within this St elment I will create an H1 element for a heading The Heading will be Color Picker after this H1 element I will create a nested div element this nested div element will have a class name equal to color- display this is what's going to change color this development now I will set the style attribute equal to some Java script if I attempt to set the background color to our color variable well with any CSS properties in JavaScript we need to enclose them within an object so we will use a double set of curly braces and that would work if you're embedding some JavaScript and then you're changing some CSS properties you'll need to enclose those CSS properties within a JavaScript object within this Nesta div element we'll create a paragraph element ment that has text of selected color embed some JavaScript include our stateful color variable after this development I will create a label this label will have text of select a color I'll create an input element input the type attribute is going to be color we'll have an input element for a color the default is black I'll set the value equal to our state full color variable then to change the color I will set the onchange event handler equal to a call back to a function we will handle color change but we still need to to Define this function that's the last step in this component so we will create a function to handle color change there will be one parameter an event all we're going to do is use our Setter function for our color whichever color we select that's going to be its value either RGB hsl or hexadecimal we will access this event Target access its value set the color to whatever that value is so if I set the color to be I don't know blue well that color is going to change to be blue and that is everything we need for this component we haven't applied any CSS yet so it's not very impressive although it does have functionality so be sure to save everything we will go to our CSS stylesheet let's select the body of our document I will set the font family to be aial with a backup of s serif I will take our class of Color Picker container this is what contains everything this div element take our Color Picker container I will use flexbox because I like flexbox display Flex Flex direction will be a column right now it's a row and align items in the center much better let's take our H1 element that would be this heading we are selecting H1 let's add some margin of 50 pixels and increase the font size to 3 r let's select our color display that would be this element right here that has a class of color- display I will set a width of 300 pixels a height of 300 pixels I'll use flex box for all the elements within display Flex justify content in the center then align items Center I'll add a border around this element border 5 pixel solid I'll use hsl for the color let's pick something light gray I'll set the lightness to be 80% then I'll round the corners with border radius border radius 25 pixels I'll add a little bit of margin to the bottom margin bottom 25 pixels so when we select a color it's going to change I'm going to add a transition effect so the transition is a little more smooth I will set the transition property after a quarter of a second 0 2 5 Seconds we will ease this transition so this animation should be more smooth let's select this paragraph element and style it take our color display class access the paragraph element within for the color I'll use hsl values 0 0% then 20% this will make the text a dark gray color although it's kind of small you can't really see it I'll increase the font size to 2 RM then text align Center let's work on the text of the label we're going to select our label increase the font size to 1.5 RM let's set the font weight to be bold and add a little bit of margin to the bottom margin bottom 10 pixels the last thing we need to do is change this input element so it's a little bigger I will select our input element but I don't want to select all input elements I'll use an attribute selector select all input elements that have a type of color so that'll be just this one I will set a width of 75 pixels a height of 50 pixels some padding of 5 pixels I'll set a border radius to round the corners of 10 pixels then set the border to be 3 pixels solid and for the color I'll use hsl zero for the Hue zero for the saturation 80% for the lightness that should give us a thick gray border all right everybody so that is a Color Picker program you can create as an exercise for react yo what's going on everybody so in today's video I got to explain updator functions in react an updator function is a function passed as an argument to set State usually for example I have a Setter function for a year if I need to increment my year by one I would just add plus one to year this does in fact work but a better practice would be to pass in an updator function as an argument usually this is represented as an arrow function by passing in an updater function this allows for safe updates based on the previous state you typically see updator functions used with multiple State updates and asynchronous functions it is a good practice to use updator functions when ever possible so in this basic example I've made a counter program we can increment count decrement count and reset count within each of these functions I'm taking my state variable of count adding + one minus one or set and count to equal zero in the case of reset I don't want to increment once I would like to increment twice I will take set count update the state again using count plus one this is different for me adding two to count I want to increment count by one twice I will set the state of count twice count + one then count plus one if I attempt to run this I will increment count twice with every button click however our count only increases by one during each button click I'm very persistent let's try and set count again because you know the first two times didn't work during each button click I would like to increment count by one three times but we're still only updating by one still here's the reason why we're using the current state of count to calculate the next state after using a Setter function this doesn't trigger an update react batches together updates for performance reasons you would imagine that after these functions we would update but that's not necessarily the case using react we batch together the State updates for performance reasons in reality it's going to look something like this we're taking count which is zero adding one to it count didn't update yet it's still zero add one to it take count which is still zero because we didn't update add one to it in reality what we're doing is setting count to be one three separate times and then updating this would be similar to me hitting the refresh button on my web browser a bunch of times we've sent a bunch of commands to refresh the web browser but we may only end up refreshing once not each time I click the button that's because our web browser has its own event Loop cycle that's a similar way of thinking about it if for some reason you need to use multiple State updates you'll want to use an updator function here's how we're going to write a function our function has one parameter count in this case Arrow then do this let's write an arrow function for each set count so this will work however you'll want to rename count to be something else we're going to be working with the previous state of count not the current state we're using the previous state of count to calculate the next state according to the react documents you'll want to rename count as either something like previous count such as this or you can take the first letter of the state variable in this case C I find taking the first letter of the state variable much more easier to read it's less ver Bose so this will work then when I press the increment button we're updating the state three separate times C represents the previous count not the current count with our updator function we're taking the pending state to calculate the next state not the current state we don't update until later when we pass in an updator function we're adding all of these updator functions to a q a q is a type of data structure a q is similar to a bunch of people waiting in line it's first come first serve the first person in line is going to be helped first so during the next render it will call all of these functions in order rather than batch them all together when using multiple State updates you'll want to be sure to use updator functions it is good practice whenever possible to use updator functions just for consistency even if you're only going to update the state once it would still be good practice to use an updator function it will help future proof your code in case you ever need to update the state again so now let's take our decrement function currently we're updating the current state of count not the previous state let's begin by setting up a parameter of count Arrow then do this but we'll want to be sure to rename count just to show that we're working with the previous state not the current state let's rename count as the first letter of the state variable which is c c arrow take C minus 1 let's do this two additional times now when we increment we will increment 3 separate times and we can decrement three separate times now last we have reset with the setter function we're not dependent on the previous state all we're doing is setting count to be zero if I was going to use an updator function it would look like this C Arrow C equals z we really don't care about the previous state this would still technically work we don't really need our count for anything we're setting c equal to zero because by passing in zero we're already setting it to be zero in this specific example an updator function wouldn't be necessary because we don't need the previous state all right everybody so those are updator functions it's a function passed as an argument to set State usually when updating a state variable you'll pass in an arrow function if we were working with a state variable of year I would pass in an arrow function that looked like this we have a parameter of Y Arrow let's take y + 1 if I was incrementing our year by one in this case by using updator functions they allow for safe updates based on the previous state not the current state this allows for multiple State updates and is used with asynchronous functions it's a good practice to use updator functions whenever possible we will be using updator functions in the future and well everybody those are updator functions in react hey everybody so in today's video I'm going to show you how we can update the state of objects be sure that you're importing the UST State Hook from react so we'll Begin by creating a constant use array D structuring our object will be a state variable of car then we need a Setter variable for this car set car equals the use State hook you can set the initial state with you state so what we're going to do in this lesson is create a JavaScript object we're going to create your favorite car with three properties a year a make who manufactured the car and a model so pick a car that you like I like a 2024 Ford Mustang if you would like although not necessary you can put each of these properties on a new line for readability personally I find that easier to read so car is going to be an object with these three properties but later on we're going to update these properties with a few text boxes within our return statement we will create a development to wrap everything I will create a paragraph with some text your favorite car is so we have that text currently We'll add our cars year followed by The Cars make then the cars model so for me my paragraph States your favorite car is a 2024 Ford Mustang after our paragraph element we're going to create three input elements one for year make and model so let's do that I will create an input element the type of this input element will be number for the year so we should have some arrows on this input element to increment or decrement I will set the initial value to equal the year of our car car doe I'll add a break afterwards let's copy this input element paste it twice the second input element is going to have a type of text for a string the initial value will be the make of our car in my case Ford the third input element will have type text the value will be model I have a 2024 Ford Mustang when I interact with these input elements I would like to change the property of my object we'll need to use the onchange event handler the onchange event handler is going to accept a call back to some functions function handle year change there will be one parameter an event the event object is going to be provided to us through the onchange event handler when we add that in in a moment let's copy this function we'll fill it in later then we will have a function to handle make change then handle model change we have our three functions to change the year the make and the model properties of our object with our input elements we will set the on change event handler equal to a call back a call back to handle year change so let's set the onchange event handler to the other two input elements onchange handle make change onchange handle model change the last thing we got to do is finish filling in our functions we'll begin with handle year change if I want to change the state of my car object I will use the setter function that's provided to us with use State set car set of parenthesis we will be using an updator function but there's something I want to explain first we're going to set our car to be a JavaScript object if I were to take the year and set it equal to 2025 this is what happens if I interact with this input element let's say I decrease this input element well the value changes to 2025 that worked but the make and the model of our car disappeared these properties no longer exist what we've ended up doing is replacing the initial object that has these three properties with a new object that has this one property of year we need some way to retain the make and model of our car the previous properties that we're not updating that's why we're going to precede this property to be changed with the spread operator of our car when we update the state of our car we're going to be creating a new new object spread all of the current properties of our car and add a year after using the spread operator it's going to look like this we'll have a year make model and year again if you have an object with two properties with the same name you'll end up using the later one and disregarding the first JavaScript doesn't allow for duplicate Keys that's why we're going to be using the spread operator on our car object than updating the year that should allow us to retain the previous properties if I were to interact with the year we'll retain the previous properties they won't change currently the setter is only set to change the year to 2025 we're going to access the event object provided to us from the onchange event handler behind the scenes I will change the year to be access our event object access its Target access its value when I interact with this input element the year property is going to change accordingly but a better practice with use state would be to use an updator function which we learned about in the last video we don't want to modify the current state of car but rather make a reference to the previous state this allows for safe updates we're going to turn this object to be part of an arrow function so let's create our Arrow function we will take our car Arrow do this so with an arrow function if you have a set of curly braces after the arrow function JavaScript thinks you're trying to write a multi-line statement but that's not the case we're trying to create a JavaScript object what you could do is surround your set of curly braces with a set of parentheses that will allow you to create an object within an arrow function since we're working with the previous state of car and not the current state we would want to name this to something else one common naming convention is to take the first letter of the state variable and use that to indicate that this is the previous state so c will be our parameter we will use the spread operator on the previous state of car represented as C and that should work this allows for safe updates especially if you're updating the state of your car more than one time within a function see my video on updator functions if you'd like to learn more about that all right then we have to handle make change we will use our setter set car we're going to be replacing the initial object with a new object we will use the spread operator on our car access the make set it equal to access our event parameter that's provided to us access its Target access its value we'll upgrade the statement so that it's an updater function let's take our car Arrow do this then we will rename car as C to indicate that we're working with the previous state of car not the current state I can change my year and I can change the make and that should update we have one last function to work with handle model change again set car we're creating a JavaScript object use the spread operator on our card to spread the properties so we don't lose them update the model with our access our event access its Target access its value then we'll change this to be an updator function we have parameter of car Arrow do this since we're creating a JavaScript object within an arrow function we need to surround it with a set of parentheses and then rename car as C to indicate we're working with the previous state and that should work I will change the year the make and the model all right everybody so that is how we can update the state of an object using react hey what's going on everybody in today's video I'm going to show you how we can update the state of an array using react all right everybody here's how we can update the state of an array using react be sure to import the UST State Hook from react we'll Begin by creating a constant use array D structuring the name of our array will be Foods because I'm hungry like you ual we'll need a Setter function for the state variable set Foods equals use State we will set the initial state to be an empty array if you would like to include some initial elements you can put that within here such as an apple an orange and a banana we'll create two functions a function to add an element to this array and another function to remove an element we'll create a function to handle add food there are no parameters and we'll declare a function to handle remove food we'll fill these in later within our return statement let's wrap everything within a div element I will create an H2 heading that says list of food we'll create an unordered list with a pair of UL tags within my unordered list we will embed some JavaScript code let's take our array of foods use the built-in map method the map method will return a new array what would we like to do with all of these elements of our array well we're provided with an element which we will name as food and an index these are the parameters that we'll receive automatically we'll write an arrow function to do something I will create a list item element we have three already because our array initially has three elements an apple orange and a banana if I were to go to my console react wants us to add a key for each list item so it can keep track of them so with the opening list item tag I will set the key attribute to equal our index within each list item I I will add the current food element and let's see if this works yes it does Apple orange banana if I were to change the initial values of this array within new state that should be reflected after the unordered list we'll create an input element to enter in the names of some food I will create an input element the type the type will be text because we're adding a string I will set the ID equal to be food input I'll add a placeholder too I will set the placeholder attribute to be enter food name after this input element let's create a button the button will have text of add food with this button I will set the onclick event handler equal to to a call back to handle ad food let's work on the handle ad food function we need to get the value found within this input element if I were to type coconut then press the button I need to get this value but first we'll select this input element to access it I will create a constant of new food new food will be a string it's going to contain this value I will access this element this input element document. get element by ID the ID that I'm getting is food input I would just like the value not the entire element so if I were to type in coconut press the button new food is going to be a string of coconut then after pressing the button I'm going to reset this input element so it clears like this I can do that by copying this line of code where we access the value set it equal to be an empty string so if I were to type in something it should reset after hitting the button which it does let's try a mango and that resets too so we have the string that contains our new food we'll use our Setter to update our array if I were to pass in a new array then add new food this is what happens I will attempt to add a coconut add food our initial values of Apple orange and banana they're all gone we've replaced the initial array with the new one that contains only one string element our new food that we're trying to add we need to copy over the previous elements of this initial state within this new array when setting the state we will use the spread operator and access our array of foods the spread operator when used on an array will spread all of these elements into separate values it'll look something like this we're replacing the initial state of this array with a new one so we need to copy the old elements over so this does work I will attempt to add a coconut and a main go however it would be best practice if we were to use an updator function we don't want to directly work with the current state of a state variable rather the previous state I will will upgrade the statement into an updator function we will take Foods Arrow do this you don't want to use the same name as the current state variable a common naming convention is to take the first letter of your state variable and use that as a parameter foods will become f for the previous state we will use the spread operator on the previous state of foods and that should work we have an apple orange banana we can add a coconut or a Maino now we're going to complete the handle remove food function there's one or two things I need to change make sure we use camel case naming convention I accidentally made the r lowercase there's going to be one parameter an index number because we'll be working with the index numbers of these list item elements within our unordered list we'll be working with the opening list item tag just for readability I'm going to put this on a new line like so within the opening list item tag we will set the onclick event handler equal to a callback a call back to the handle remove food function this function needs a parameter in order for us to pass in a parameter to the handle remove food callback we need to convert this to an arrow function we'll create an arrow with no parameters Arrow do this within the map method we're provided with an index number we'll be passing in that index number to this function so we can work with it within the handle remove food function we will use the setter for our Foods within the setter we'll use the filter method we will take our Foods use the built-in filter method of arrays with the filter method of an array we are provided with an element and an index number for that element however we do have a naming conflict we've already stated that the parameter of this function is going to be index just to differentiate it I'm going to rename index as I so within the filter function we will use an arrow function to do something we're going to filter all elements where the current index represented as I does not equal the index that we receive so if you take a look our element parameter is provided to us but we're not using it you can see that it's kind of grayed out we're going to replace this with an underscore using an underscore for a parameter is a convention to indicate that the parameter being passed to the function is ignored so with parameters if you see an underscore that means ignore it all right and this should work I will add a coconut a mango then I can click on one of these list items to remove it let's remove our banana our Apple and the mango all right everybody so that is how we can update the state of arrays using react hey everybody in today's video I'm going to show you how we can update the state of an array of objects if you're able to comprehend this lesson and you've watched previous topics we'll be ready to make a few projects and react so let's get started like we've done in Prior lessons be sure to import the UST State hook in this topic we're not going to create one state variable but four const cars cars is going to be an array of objects then we need a Setter for our array of cars equals use state I'm going to set the initial state to be an empty array then we will create a state variable for the cars year and a Setter for car year use state if we're going to be adding car objects to make it easier for me I could set the initial state to be a year like 2024 something that's kind of recent but I think it would be a lot cooler if we use JavaScript to get the current year right now I'm filming this video in December 2023 for the initial state I'm going to create a new date object then get the full year method for me this is going to turn 2023 but depending on when you're watching this video it might be later we'll create a state variable for our cars make who manufactured the car set car make equals use State I will set the initial state to be an empty string then we need the model I'll just copy this because I'm lazy change make to be model set car model the initial State for the model will be a string all right now we're going to declare all the functions we'll need throughout this application we'll create a function to add a car remove a car change the year change the make change the model five functions total we'll declare a function to handle add car then a function to handle remove car are there is one parameter an index what is the index of the object that we're removing from this array we need a Handler for year make and model function handle year change there is one parameter an event that will be provided to us through the onchange event handler we need a function to handle make change handle make change and handle model change so we should have five functions total add car remove car change the year change the make change the model let's create our HTML elements So within our return statement I will create a div to enclose everything let's create an H2 element for a heading list of car objects afterwards I will create an unordered list we will populate this unordered list later we will create three input elements for the year the make and the model of our car that we're trying to add we will begin with input that has a type of number I will set the value to equal this state of car year and for me that's 2023 that's because I'm creating a date object of the current date and time then returning the year depending on what year you're watching this it might be different I will set the on change event handler equal to a call back to handle year change I'll add a break afterwards okay let's copy this input element including the break the type of the second input element will be text the value will be the cars make who made the car the onchange event handler will be a call back to handle make change we should add a placeholder to tell the user what we want them to type in it's not very apparent I'll put this on a new line for readability I will set the placeholder attribute equal to enter car make let's copy this element paste it for the third input element the value will be car model the onchange event handler will be a call back to handle model change the placeholder will be enter car model then we'll create a button to submit our car object button the text on the button will be add car we will set the on click event handler equal to handle Adar all right now we have to fill in these functions we'll begin with handle year change because it's easy we will use the setter for set car Year we will pass in Access our event object that's provided to us access its Target access its value then we have to do this with make and model set car make access the value of the target of the event pass it as an argument set car model again take our event access its Target access its value so now we should be able to update these values let's try it when I click on the button I would like to add this object to my array of objects within our handle Adar function we have a few things to write it's not as complicated as what you think it might be using these State variables of year making model we will create a new car const new car equals a JavaScript object with these properties the year will equal the current state of car year the make will equal the current state of of car make the model will equal the current state of car model then just for readability I'm going to put all these properties on a new line not necessary but I find it easier to read we will use the setter for our array of car objects we will use an updator function we will take cars Arrow create a new array use the spread operator on cars we need to copy the previous elements over to the new array we don't want to lose them then we will add a new element our new car object so we don't want to use the current state of cars but rather the previous state with this updator function a common naming convention for your parameter is to use the first letter of that state variable let's rename cars as C so what we're going to do now is go to our unordered list we need we need to populate it with list items I will embed some JavaScript take our array of cars use the built-in map method to return a new array we're provided with two arguments an element and an index with the map method but I'm going to rename element as car so it's more understandable what would we like to do I'll use an arrow function we will return a list item element and for readability I'm just going to place these on a new line react wants us to add a key to each list item element so let's take care of that I will set the key of each list item element to be our index that's provided to us within each list item element I will display the cars year followed by The Cars make and the cars model all right let's see if this works let's add a 2023 Ford Mustang and that worked how about a 2024 Chevrolet Corvette and a 2022 Dodge Challenger one thing I'm going to add to the handle Adar function after submitting a car I would like to reset these values at the end of this function let's use the setters I will set the car year when we're done with it to be the current year we'll create a new date object get the F year update the state to whatever value is returned we'll use the setter for the car make and reset it to be an empty string same thing with the car model all right let's see if this resets 2023 Ford Mustang and it does 2025 Chevrolet Camaro and that does reset you can see that my year went back to 2023 even though I adjusted it to 2025 the make and model were both replaced with empty strings now I would like to remove a car when I click on one of these list item elements we'll make one change to the opening list item tag I will set the unclick event handler to a call back to handle remove car we do have to pass in an argument though to this function we have to pass in an index what is the index of the car we're trying to remove if I attempt to pass in an argument we will call this function right away we will convert this call back to an arrow function that has no parameters So within the handle remove car function there's not a lot to write we will use the setter for our cars we'll use an updator function we don't want to use cars but we'll use the first letter to indicate we're working with the previous state arrow take the previous state of our array of cars represented as C use the built-in filter method we will filter any cars that don't meet a certain criteria the filter method provides us with an element and an index but we do have a naming conflict we already have a parameter with the name of index let's rename the index of each element within our array as I then do this with an arrow function we'll write our condition check to see if the index of the current element I is not strictly equal to the index we would like to remove we'll filter out that element when we create a new array so we're not working with the current element even though it's provided to us so what people do as a convention if you have a parameter you're not using people will change the name of that parameter to be an underscore that tells other people to ignore this parameter and that should work let's run and test everything let's add a 2023 forward Mustang but feel free to pick some different cars 2024 shev roll Corvette 2022 Dodge Challenger and I should be able to remove a car when I click on it that list item element our Corvette is gone our Mustang and our challenger all right everybody so that is how to create an array of objects and update their state using react hey everybody in today's video I'm going to walk you through creating a to-do list app using react so sit back relax and enjoy the show all right let's do this everybody we'll need to create a new jsx file going to our source folder we will rightclick new file this component will be named too list. jsx this will be a function-based component function to do list no parameters then let's be sure to export it because because if I don't do it now I'm going to forget export default to do list we will be using the use State hook we should import that import react use object D structuring I would like just the use State Hook from its location of react we do need to return something for now we're just going to return a fragment going back to our app component we need to import our to-do list component component import to-do list from its relative file path SL too list. jsx we will return one to-do list component and we are ready to move on within our to-do list component we will have two State variables const tasks tasks will be an array of strings we need a Setter function for tasks set tasks equals the use State hook the initial state of tasks is going to be an empty array but eventually we're going to populate this array with strings one string for each task to add and we will create a state variable for a new task new task is whatever we're currently editing with the text box we will be adding our new task to our array of tasks then we need a Setter function for new task set new task equals U State the initial state will be an empty string let's declare the functions we'll need throughout this program we will need a function to handle input change there will be one parameter an event this function is for our text box when we type in something we'll need a function to add a task function add task there will be no parameters function delete task there will be one parameter an index an index of the list item we would like to delete let me scroll down a function to move task up there is one parameter an index what is the index of the list item we would like to move up within our list and a function to move task down we will also accept an index okay and these are the functions we'll need until we fill these in I'm going to close these functions okay now we'll go to our return statement we have a lot of HTML elements to add we'll begin with a div element our div element will have a class name of two do list within this development we'll create an H1 ment for a heading The Heading will be a to do list after this H1 element I'll create another div element within this div element I will create an input element this will be a self-closing tag just for readability I'm going to place each attribute on a new line we have a lot of attributes to write I will set the type of this input element to be text I'm going to zoom in so you can see it more easily I'll add a placeholder of enter a task dot dot dot enter a task I will set the value of this text box to be some JavaScript our new task State variable this one when we type within this input element we will use the onchange event handler equal to a callback to a JavaScript function a callback to handle input change we'll fill in this function since we're here going to handle input change we will use the setter for our new task access our event parameter access its Target access its value so when we type within the text box it should change eat breakfast if we didn't set the new task and we type within the text box we don't see the text it doesn't change that's why we need this function so we can see the text when we write within the input element let's scroll back down to the bottom after our input element we will create a button element with text of add to add a task for the class name of the button we'll set the class name attribute of the button to be add button add- button I will set the onclick event handler equal to a JavaScript call back we will call the function of add task now temporarily until we apply some CSS I'll write a few tasks within our array just temporarily let's say our first task is to eat breakfast take a sh shower and walk the dog after our development we'll create an ordered list with a pair of O tags within this pair of O tags we'll be embedding some JavaScript we have a lot to write we're going to take all of our tasks and use the map method we will create a list item element for each task for each element within this array we'll use the map method we're provided with two parameters the current element and the index of the current element but I'll rename this element parameter as task so it's more easily understandable within the map method we will use an arrow function what would we like to do with each task I'll put this on a new line we will create a list item a list item element So currently we have three list item elements now react wants us to add a key for each element so it can more easily keep track of each element with the opening list item tag I will set the key attribute equal to the current index within the list item element I will create a span element for some text the class name for this span element will be text this will be for the text of each list item element within the span element we will include the current task we have three tasks eat breakfast take a shower walk the dog after our span element we'll create a button element this button element will be for a delete button to delete this task this button will have a class name of delete dasb button I will set the onclick event handler equal to a call back a call back to delete task now we do have to pass in a parameter the index of the list item we would like to delete delete task pass in the urrent index with a call back if you add a set of parentheses right away when we pass in an argument this will call the function right away instead we will use an arrow function to prevent that let's copy this button paste it we'll now create a move up button to move a task up if we need to change the priority the text on the button will be up but you know what I like to use emojis I'll use a pointer finger I think that would be more fun the class name will be move button on click will be set equal to a call back to move task up we'll be passing in the current index make sure that this is an arrow function too let's copy this button again paste it this next button will be for moove task down we can either write down for the text or I'll use an emoji for fun down all right and that is all the HTML that we need before we fill in these functions let's apply some CSS to everything I'm zoomed in to 100% currently let's select the container of to-do list this development so this has a class of to-do list let's change the font family to be aial with a backup of son serif text align Center denter the text and add a little bit of margin to the top of 100 pixels let's select our H1 element in increase the font size to 4 RM then we'll select all buttons increase the font size to 1.7 RM set the font weight to be bold add some padding around each button padding 10 pixels by 20 pixels set the font color to be white we'll add some background color pretty soon remove the border border none border radius to smooth the corners by five pixels change our cursor to be a pointer when we hover over a button that does appear to work we'll add a transition effect when we hover over a button let's change the background color and have it ease after 0.5 5 Seconds let's work on the background color of the buttons next we'll select the class of add button add- button pick a background color I'll pick Green but I will use hsl values I've already pre-picked a color now when I hover my cursor over the add button access the hover sudo class take the lightness make it 10% darker let's do this with the delete button let's copy what we have paste it for the next set change add to delete I'll pick a red color again I've already picked some values and when I hover make the shade 10% darker and the move buttons I'll make the move buttons blue again I've already picked a color not bad it looks like with the transition I forgot to add s for seconds that's better we'll work on the input element next so after our buttons let's select our input element we'll select all input elements that have a type attribute of text I'll increase the font size to 1.6 RM add a little bit of padding 10 pixels add a border two pixel solid pick a color I'll set the lightess to be 80% but lower the alpha to 50% not bad border radius to smooth the corners five pixels and for the font color H let's find something I'll just lower the alpha to 50% here's the text currently I'm happy with that we'll work on the list items we'll begin with our ordered list remove all padding padding zero so that should delete the numbers we will style each list item element increase the font size to 2 RM set the font weight to be bold add some padding of 15 pixels change the background color I'll set the lightness to 97% add some margin to the bottom of each list item of 10 pixels to separate each of them add a border three pixel solid pick a color for the lightness I'll pick 85% and the alpha down to 75% border radius to round the corners 5 pixels for the elements within each list item I'll use flex box display Flex to align everything and align items Center I would like the text to take up as much space as possible so I will select the class of text use flex box set it to One Flex one it's a shortcut for these three CSS properties Flex grow Flex shrink and flex bases this is more advanced Flex box if you set an element to have Flex one you're applying these three properties basically speaking that element should take up as much space as possible and grow and Shrink with the size of the web browser so all these buttons are going to be pushed to the right because the text wants to take up as much space as possible okay now we will select the class of our delete button and move button these two sets of buttons let's add some padding 8 pixels by 12 pixels increase the font size to 1.4 R I'll add some margin to the left of each button margin left 10 pixels much better this is optional but I'm going to change the background color of the body of my document I will select the body change the background color I'll go with a dark gray color I'll set the lightness to 10% I'll also take our H1 element and set the font color to be white I think that looks pretty good but you don't necess neily need to change the background color if you don't want to our CSS is now done we just have to add some functionality let's go back to our to-do list component we'll begin with add task after hitting the add button we'll call this function to add a new task we have to get the text within this text box we'll use the setter for set tasks pass in a new array spread the current elements of tasks and add our new task that state variable we should update this to use an updator function we will use the previous state of tasks represented as T Arrow spread the previous state of tasks represented as T we would like to clear this input element so we can set new task set it to be an empty string to reset it now we should be able to add a new task go to work and add and and that has worked eat lunch now if somebody doesn't type in anything they can still add a task to prevent that with an add task we'll wrap everything within an if statement take our new task use the trim method to remove any white space if after removing any white space if this is still strictly not equal to an empty string then add a new task so now when I try and add an empty task it doesn't do anything let's add some text go to work and that will work the add task function is now done let's work on delete task delete task provides us with an index an index of the element we would like to delete maybe I don't want to take a shower I'm only a little bit stinky So within delete task we will create a new array of updated tasks so we need to use the filter method take our array of tasks use the filter method with the filter method we're provided with an element and each index of that element during each iteration but we have a naming conflict we already have a parameter named index for the index we would like to delete we'll rename index within the filter method as I to differentiate it Arrow then a condition if the current index of I is strictly not equal to the index we would like to delete put it within our new array of updated tasks if these two indexes match we will filter it out we don't want it cuz we want to delete it then once we have our new array of updated tasks it should be missing that element now we're currently not using this element parameter even though it's provided to us a common convention that people do if a parameter should be ignored people will change this to an underscore that's a convention to say ignore this we will set our new tasks with our updated tasks and this is an array an array that's missing one element whichever one we filter out using the filter method now we should be able to delete an element I do not want to take a shower delete and I don't feel like going to work delete delete task is now done now we need need to be able to move a task up or down using the directional buttons so let's work on task up first let's check to see if our index that's passed in as an argument is greater than zero if the element is already at the top we don't need to move it up further we need to create a new array of updated tasks equals spread the current tasks and create a new array of updated tasks to work with now we're going to use array destructuring to swap two elements within an array here's the formula we have the current index and the index minus one we will be swapping these with index minus one and the current index so take our updated tasks at the current index and the updated tasks at index minus one set these equal to updated tasks at index minus one and updated tasks at the current index I do have a separate video on destructuring if you need a refresher this code will swap two elements within an array and then we will set our tasks using the setter function set tasks pass in our updated array and now we should be able to move an element up whoops looks like we have two functions for move task up move task down all right let's see if this works and now we should be able to move these up with move task down we're going to copy everything within move task up the condition is if our index is less than our task length property minus one if our element is already at the bottom we don't want to move down any further take index + one and then update our tasks now we should be able to move tasks up and down and even add new tasks and delete tasks and of course to initially have no elements within this array we can delete all these so then we start with an empty array all right everybody so that is a somewhat extensive program to create a to-do list applic using react hey everybody we have an important topic to discuss today and that is the use effect react hook use effect is a react hook basically speaking use effect tells react to do some code when then pick one of the following do some code when this component rerenders or do this code when the component mounts when you mount a component that's when you create and append it to the Dum that is known as mounting or do some code when the state of a value changes think of an effect as some side code you would like to perform I don't really think use effect is a great name if I could rename use effect I feel like a more appropriate name would be use side code but that's just my opinion so think of an effect SM side code you'll write your side code within a function this can be a callback an anonymous function or an arrow function and optionally for the second argument you can pass in an array of dependencies if we would like to run our side effect on every render of the component we would just need to pass in a function such as an arrow function do this code every time the component renders if you would like to perform some side code only when the component mounts and not during every render you would pass in an empty array of dependencies that tells react perform this code only once when the component mounts within your array of dependencies if you were to pass in a value this code would run when the component mounts plus when this value changes use effect has a bunch of different uses you'll see use effect with event listeners do manipulation subscriptions to real-time updates fetching data from an API and clean up when a component unmounts unmounting is when you remove a component from the DOT whereas in mounting is adding a component to the Dom okay let me give you a few examples in order for us to use use effect we have to import it from the react Library we have use State as well as use effect in this example we're going to create a count State variable const count and a Setter for count set count equals use State the initial state of count will be be zero and we'll display our count within our return statement let's create one paragraph element that has text of count as well as our state variable of count and a button let's create a button element that has text of add when we click on ADD we will add one to our count we'll need a function to work with I will set the onclick event handler equal to a JavaScript function let's name this function add count then we just need to declare this function function add count all we'll do is use our Setter for count take the previous state of count as a parameter Arrow do this take the previous state of count add one every time I press the button we will add one one to count now let's use use effect I can run some side code every time this component renders I would just have to place that code within a function that will pass to use effect every time this component renders I will change the title of the document we'll need to use use effect be sure to place use effect near the top of your component we will call use effect there are two arguments a function and an array of dependencies I would like to perform some code every time the component renders I do not need that second argument now we just need a function this can be a callback an anonymous function or an arrow function we're going to be using an arrow function every time this component rerenders what would we like to do let's access our document access the title set it equal to be a template string of count and insert our state variable of count Let me refresh every time this component rerenders including initially when we Mount the component we will perform this code where we update the title every time I press the added button the title is going to update if you would like your side code to run only when the component it mounts when we create and add it to the Dom initially you'll pass in as a second argument an empty array an empty array of dependencies so if I were to run this again and press add well our title only updates once and no other time after that for example I might want to set my title to be my counter program I only need to update this title once I I don't need to update it every time the component renders it's a oneandone effect in this case I would like to add an empty Ray of dependencies because if I didn't well we would update this title every time the component renders when we really don't need to in this specific example it doesn't benefit us to update the title every time we add one to count let's revert those changes back you could pass in a value to your array of dependencies within your array of dependencies you can add a value let's add our count State variable what we're telling react is that when our component mounts plus when this value changes of count then do the side code so with what I've written currently every time I press the button the title is going to update if our count State variable updates perform our side code this is very s similar to us not having that dependency array you know this will work too however since we don't have any dependencies this code is going to run for any reason that this component rerenders even for something completely unrelated by adding an array of dependencies and placing a value within do this code only when this value updates now to demonstrate we'll create another button to subtract the text will be subtract we'll create a function to subtract count we can copy this function paste it change the name to subtract count take the previous state of count minus one so if our count changes whether we add one or minus one the title of our document is still going to change if the value of count changes for any reason do the side code let's add another value to our dependency array we will create a state variable for color color and set color equals use State the initial state for my color will be green we'll flip between green and red green means go red means stop after our subtract button I will add a break and button two change the color change color the onclick event handler will equal this function of change color and we just need to Define this function function change color we will use the setter for set color we will use the previous state of color is the previous state of color strictly equal to Green tary operator is this true if it is return Red otherwise return green then we will take our paragraph of count access the style attribute set it equal to embed some JavaScript we need a JavaScript object so we need another set of curly braces take the color property set it equal to our color State variable so now the count is green with our title let's also add the color so I'm not going to add our color to our dependency array quite yet we can add the title updates we can subtract the title still updates but if we change the color the color changes of this paragraph element but not the title we're executing this code only when the count changes so even though I'm flipping between red and green the title is still staying the same if I were to add our color to our dependency array anytime the count or the color changes update the title so let's try this again the title updates when I add or subtract or change the color now the title is count one red count one green count one red count one green so that's where your dependency array comes in anytime one of these values change perform the side code now you may have noticed if you remove use effect well your title is still going to update so why would you need use effect there are a couple benefits of using use effect the first benefit is that by using use effect it keeps your code more organized if you were to look over some react code and look within the use effect hook you could tell when exactly this code runs does it run during every render only when the component mounts or when one of these values change if you didn't use use effect well then this code would run every single time regardless every time the component rerenders which you may not always want but not only that but with more advanced features such as event listeners or subscriptions you may want to remove or free up those resources you can return a cleanup function if you were to return a function when this component unmounts when we remove it from the Dom or before the next render you can perform some cleanup code for example if we were to add an event listener when the component mounts we would like to remove it before unmounting if we don't it may lead to unexpected Behavior so that's another benefit of using use effect perform some code only in certain situations and you do have the option to do some cleanup code before the next reender or when you unmount the component I'll discuss the return statement in this next demonstration and how it can be useful in this next example we're going to create a width and a height what the width and the height of our window is every time we adjust the size of the window the width and the height displayed is going to change we'll need two State variables to work with a width set width we will be using use state so the initial state of the width of the window access our window give me the inner width property then let's do this with height const height set height window do inner height within our return statement we will create a paragraph element that has text of window width we will display our width State variable then add pixels for a unit of measurement then let's do this with height window height display our height State variable so we have window width and window height if I were to adjust this window nothing happens there's no change let's create a function to handle size function handle resize no parameters we're going to set our width to be the inner width property of our window and set height H should be Capital set height take our inner height of our window and reset it so now we need to add a an event listener because this still doesn't change we're going to add an event listener that will listen for a resize event whenever we resize our window if we attempt to use this without use effect but within the body of our component we will take our window add an event listener we need an event and a function to do something the event is going to be a resize event when the window is resized perform this code we will pass in a call back to handle resize and then for demonstration purposes I'm going to console.log event listener added we only need one event listener to make this program work now if I were to resize my window this does work our width State variable changes same thing goes with the height now let's take a look at our console there's an issue we only need one event listener to make this program work however every time the component rerenders we're adding a new event listener we have added over 1,000 event listeners that's really not good how about this only when our component mounts when we append it to the Dom we will add one event listener and that's it so guess what we're going to place our code within use effect we will pass in a function and an array of dependencies when would we like to add an event listener let's add an event listener only when the component mounts so we need to add an empty array of dependencies let's try that again I'm going to resize our window that should be good go to inspect yeah you can ignore all this garbage so if you have strict mode on which I do use effect is going to run twice it will run a development only setup and then a cleanup cycle so this is normal so we didn't add thousands of event listeners besides the first cleanup cycle because I have strict mode on we're only adding one event listener because that's all we need we don't need thousands of event listeners if you ever need to unmount the component meaning remove it from the Dom use effect has another use and that is adding a return statement to do any cleanup you will return a function do this code either before the next render or when the component unmounts if we add an event listener then we unmount the component it would be good practice to remove that same event listener if you don't that can lead to unexpected behavior when and we unmount our component we will take our window then remove event listener we will remove the event of resize and a call back to handle resize when we are done with this component free up any resources so that it doesn't lead to unexpected Behavior let me add one more line of code too let's console.log event listener removed let's refresh resize our window a few times go to inspect console okay let's take a look since I am in strict mode we'll run our use once during the development cycle and then clean it up right away then we will add that event listener only once we didn't unmount this component yet so we didn't remove it so by adding a return statement you can do any cleanup either before the next reender or when you unmount the component within a component you can add more than one use effect hook we're going to add a second use effect hook if the width or the height changes we're going to update the title of our document to display the width and the height so let's add a another use effect hook use effect what code would we'd like to perform let's access our document take the title set it equal to be let's use a template string let's say size placeholder width x height when would we like to use this effect let's use this effect when the width and the height update we will need that dependency array we will list the width and the height State variables so on Mount we'll get the size right away 227 by 396 now every time the width and the height changes the title is going to update so you can have more than one use effect hook within your component all right everybody so that is the use effect hook it's a react hook that tells react to do this code when either the component renders this component mounts or the state of a value changes there are two arguments a function that contains the code you would like to perform and optionally an array of dependencies based on what you pass in to use effect you'll either run this code after every render run only when the component mounts or run when the component initially mounts plus when the value changes use effect is great with event listeners Dom manipulation subscriptions to real-time updates fetching data from an API or cleanup when a component unmounts we will have more practice with use effect in the next video where we will create a digital clock and well everybody that is an introduction to use effect in react hey everybody in today's video I'm going to show you how we can create a digital clock using react so sit back relax and enjoy the show okay let's get started everybody if you would like a background image for your app place that image within your assets folder here's the image that I'm going to use I found it online we will create a digital clock component within our source folder digital clock. jsx we will need to import two hooks import from react use object destructuring to get the use State hook as well as the use effect Hook from its location of react we're going to create a function based component of digital clock no parameters then be sure to export it at the end export default defaulty default digital clock we do need to return something for the time being we are going to return a fragment just so that everything runs back within our app component we need to import our digital clock component from its locationd digital clock. jsx we will include one digital clock component within our digital clock comp component we'll create the following HTML we will create a div element to contain everything this outer div element is going to have a class name of clock container within this development we will create a nested development this development will have a class name of clock we have a clock within a clock contain container within this in div element we will create a span element to display a time until we get the time working let's display a bunch of zeros for the hours minutes and seconds and here's our time but it's a little small I'm zoomed in currently okay let's go to our CSS stylesheet we will select the following the body of our document our clock container class and our class of clock if you would like to add a background image here's what you can do within the body of your document we will set the background image property to be we will use the URL function within this function we will pass in a relative or absolute file path to your image from the index file we'll have to access the assets folder asset that's the name of the image my image is named background and this is a JPEG okay here's my image but it's a little big then we will take our background position property set it to be Center to Center the image now it does repeat we'll set the background repeat property to be no repeat we'll set the background size to cover to cover this div element the outer div element background size cover now we'll take the background attachment property set it to be fixed as we adjust the size of the window the image is going to adjust accordingly and maintain its aspect ratio we do have a little bit of margin around the body of our document I'm going to remove that margin zero next we have to work on the clock itself it's a little small within the clock class I will set a color of white I'll increase the font size CU we can barely see it to 6 RM that should be a decent size and a font weight of bold pick a font family I will pick monospace I think that'll look good for a clock I will also add a text Shadow effect with a horizontal and vertical offset of three pixels each and a blur of five pixels pick a color I'll pick black but I'll lower the alpha to 75% or so then I will Center align my text text align Center our clock is centered horizontally but not vertically within the window if you would like the clock in the exact middle of the window here are some following optional CSS properties you can add these are optional we'll use flex box display Flex to display all the elements justify content Center to Center this clock vertically within the middle of our window we have to set the maximum height of the body to be 100% of the viewport height we'll add this following property set the minimum height of the body to be 100 VH for the viewport height 100% of the viewport height then use the Align items property set it to be Center to vertically align it and I think that looks pretty good now we'll select our clock container for the background of the clock container I would like it so it looks like we're looking through glass here's how to do that we will use the backdrop filter property use a function of blur pass in a number in an amount of pixels the greater the number the greater the blur here's five pixels here's 50 what's 500 look like okay let's go with five pixels we have a little bit of a blur effect if you would like the clock container to take up 100% of the viewport width you can add the following property set the width of the clock container to be 100 VW for viewport width so now the clock container takes up 100% of the width of the window then I'll add a little bit of padding to the top and bottom but not the sides padding 10 pixels for the top and bottom zero for the sides we should get a little bit of padding on the top and bottom I like that I think that looks pretty good okay we can save everything we no longer need our CSS stylesheet and now we will be working within the digital clock component we'll be using the uate hook we will create a state variable of time const time and a Setter for time named set time equals the use State hook for the initial state of the use State hook we will pass in a new date object whatever the current date and time currently is that's what the initial state of time is going to be it will be an object we will also use the use effect hook we can perform some code during each render or when we Mount or anytime some sort of value updates when this component mounts we'll start an interval to move the clock forward there's two parameters within use effect a function to do something and an array of dependencies for our function we'll use an arrow function parameters Arrow do this and for our dependencies based on the last video we're just going to set an empty array I would like to start a timer only when when we Mount the component we don't need to start a new timer every time the component renders what would we like to do once when our component mounts we will create a constant of interval ID equals set interval with set interval we can pass in a call back and a time in milliseconds to repeat this call back let's do some code every 1,000 milliseconds meaning every 1 second let's do the following we'll write an arrow function to do this every 1,000 milliseconds we will update the state of time using our Setter of set time we will pass in a new date object and that's all we need so after every second we will update the state of time with the new current date and time now if we do unmount this component it would be good practice if we were to clear our timer if we don't it may lead to unexpected Behavior we will add a cleanup function when this component unmounts we will return the following do this function we will call the function to clear interval and pass in that interval ID to stop this interval if we ever unmount our digital clock we don't want it to continue running we want to free up any resources if we don't that may lead to unexpected Behavior so that is all we need with use effect when we Mount and that's it create an interval that updates once every second when we unmount the component clear that interval and that's it now we will also need a function to format time function format time there are no parameters we need to get the hours minutes and seconds of our time the state variable of time that's pretty simple though we will declare using let let hours equals our time State variable use the method of get hours let's do this with minutes let minutes actually let's declare this as const const minutes time. getet minutes and seconds const seconds equals time.get seconds we will also find what the meridium is is it am or p.m we'll have to write the following const meridium equals let's examine our hours is our hours greater than or equal to 12 our time in hours is going to be in military time I believe that's 0 through 23 technically if ours is greater than or equal to 12 tary operator if this is true meridium will be PM otherwise meridium will be am with hours we're going to reassign it let's say that it is 1 p.m. so hours will be 13 1 hour after 12 if I don't want to display my time and military time I'm going to reassign hours we'll take hours modulus 12 modulus gives you the remainder of any division for example if ours is 13 13 modulus 12 has a remainder of 1 so that's how you can convert from military time use modulus 12 what if ours is 12 12 modulus 12 is 0o if it's 12:00 we don't want to display zero we can add the following use the or logical oper operator or return 12 if this equation is zero that is equivalent to false so using the or logical operator ours would instead equal 12 then within format time we're going to return one long template string we will display a placeholder with ours colon a placeholder with minutes colon a placeholder with seconds space placeholder our meridium then within our span element we will display embed some JavaScript called The Format time function here's the current time for me it is 7:52 at night p.m. and the time is updating now we have a problem if one of our units of time is a single digit we don't have any leading Zer so let's fix that we will declare a function function pad zero there's one parameter we have to pass in a number with hours minutes and seconds we will pass each of these units of time to the pad zero function so we will enclose each of these within the pad zero function then return a result so let's pad our hours with zero pad our minutes with zero and Pad seconds with zero okay we have undefined undefined undefined that's okay so within pad zero we have to return something we need to check to see if our number is a single digit we can do that with checking to see if number is less than 10 if it is it's a single digit we'll use the tary operator is our number a single digit is it less than 10 if that's true we're going to return a string of zero if not we don't have to do anything we'll return an empty string we will take all of this and close it within a set of parentheses return either zero or an empty string plus the original number for example if our number was 1 1 is less than 10 that is true we'll return a string of zero the new string concatenation and add our original number of one so we would return 01 if our number was 12 well this condition is false we would return an empty string plus the original number of 12 which would give me a string of 12 so here's the result we have each unit of time with the leading zero if it needs it and we have success F created a digital clock component and the cool thing about doing this in react is that we can reuse this component whenever we want we can create one digital clock component or another or another or another and Let me refresh these to synchronize them these are all individual components running their own code all right everybody so that is how to create a digital clock component using react hey everybody today I got to explain use context in react use context is a react hook it allows you to share values between multiple levels of components without passing props through each level what we'll do in this example is create four components components a through D each component will be nested within one another so within our source folder let's create a new file for component a this will be a jsx file we will create a function based component named component a no parameters for now and be sure to export it export default component a within this component we will return some HTML we will return a div element the div element will have a class name of box within the div element we will create an H1 element that as text of component a within our app component we will import component a import component a from its location component a. jsx we will return a single component a component we're also going to add a little bit of CSS to visualize it we will select our class of box add a border of three pixel solid and padding of 25 pixels here's component a we're going to copy this file of component a and paste it three times we will rename the second copy as component B the third as component C the fourth as component D we have component a b c and d within component B rename any instance of component a with component B the same goes for C and D from component a we're going to import component B import component B from its location component b. jsx after our H1 element we will include one component B component we have component B within component a now within component B we will import component C import component C from its location component c. jsx after our H1 element we will include one component C component so we have component C within component B within component a within component C we will import component D import component D from its location component d. jsx after our H1 element we will include one component D component we have component D within component C within component B within component a I've organized my tabs a b c d within component a we're going to create a state variable const user and a Setter for user equals the U State hook we will need to import it type in your username I'll type in bro code for mine at the top we need to import from react use object destructuring to get the use State Hook from its location of react now after our H1 element I will create an H2 heading we will embed some JavaScript we'll display a template string of hello add a placeholder your username So within component a you should have an H2 heading that displays hello and your username within component D what if I would also like to display my username well from component a I would have to pass props down all the way to component D I'll have to pass them to B which will pass them to C which will pass them to D so if we were using props this is what we would have to do within component B we will pass in props set user to equal our user within component B we'll have to set up props props will be the parameter within component C we will set user to equal embed some JavaScript props do user within component C we'll set up props again within component D we will set user to equal embed some Java JavaScript props do user then within component D set up props again after our H1 element let's create an H2 element we'll embed some JavaScript use a template string display by add a placeholder access props our parameter access the user within component a we have hello your username within component D we have by your username by passing props down each of these nested components this is known as prop drilling where drilling down to the center the center component passing props down this long chain can become very tedious but there's a better solution and that is with the use context hook the use context hook allows us to share values between multiple levels of components without passing props down through each level however we have to set up a provider component which component has the data we would like access to in this case it would be component a in component a we have that state variable of our username which we named user So within our provider component we have three steps we have to import create context from react So within component a we already have used state but we also need create context we need to create some context and Export it export const then we need a unique name for this context we're working with the username let's name our context user context the context name should be descriptive of what you're working with if the data we're working with as a color we could say color context equals create context and this is a function now the last thing we need to do is wrap any children components with within this special provider component we are going to wrap component B within another component we will take our user context access provider set the value equal to be some JavaScript our value of user and we just need to wrap this component of component B component a is now the provider component it's going to provide a value of user we no longer need props we can get rid of these for each component after I deleted props from component B well our username is now undefined within component D we broke that chain all right any component that needs this data we will set up to be a consumer component you can have more than one we'll have to import the use context Hook from react as well as the context that we set up we're exporting it so we need to import it elsewhere within component D we will import from react use object destructuring the use context Hook from its location of react we also need the user context import use object D structuring to get user context from its location of component a that was the original location where we exported it from we'll use the context get the context and store the value we'll do that inside of our component const user equals use context hook we're going to pass in our user context as an argument and now we have access to user we'll use a placeholder and add our user and that has appeared to work we have displayed bu your username we have avoided prop drilling instead of drilling down to the center component to pass down a value by using use context we Traverse up the component tree to find the nearest provider which would be component a component a is the provider component component D is a consumer component and you can have more than one so let's do the same thing with component C we need these two lines of code really we can just copy them because I'm lazy and we need to create a constant of user or some other descriptive name for this value use context pass in our context of user context let's add another H2 element we'll embed some JavaScript use a template string let's say hello again add a placeholder our username So within component C we have used use context again without prop drilling we're just playing hello again your username any component that's a child component of our provider component of a has access to this value that we set up all right everybody so that is the use context react hook it allows you to share values between multiple levels of components without passing props through each level if you have a lot of nested components passing props down to each level can become very tedious this is a way to avoid that and well every everybody that is the use context hook in react okay let's do this everybody we got to talk about the use ref hook in react use ref meaning use reference is very similar to use State use state store some sort of value or an object or an array whenever the state value changes use State renders the component which isn't always what we want use ref meaning use reference it does cause reenders when its value changes use use ref when you want the component to remember some information but you don't want that information to trigger new renders use ref is helpful with accessing and interacting with dom elements handling Focus animations and transitions as well as managing timers and intervals use State triggers renders use ref doesn't in order for us to use the US ref hook we have to import it from react import use ref for this sample program we'll be using UST State originally then we'll switch it up and use use ref to see the differences we'll Begin by using the use State hook we will have a state variable of number and a Setter for number equals U State I will set the initial state of number to be zero we will return a button element the button will have text of Click me I will set the onclick event handler equal to a function of handle click then we just need to declare this function function handle click no parameters what do we want to do when we click on the button let's use the setter for number and increment the previous state of number by one n + one whenever my number updates it's going to cause my component to render I can demonstrate that with the use effect hook so before our function of handle click let's use use effect with use effect if we don't pass in a dependency array we'll perform some code every time this component renders so for this demonstration let's console.log component rendered anytime this component renders using effect is going to execute this code where we display component rendered so I'm going to go to my console when your component mounts you'll render your component twice that's if you're in strict mode just temporarily for this demonstration I am going to remove strict mode so our component renders once on Mount whenever we update the state of a state variable that causes the component to reender that's where use ref comes in use ref doesn't cause a component to render when its value changes it's kind of like an escape hatch so instead of using a state variable we're going to use ref use ref means use reference we're referring to something we will declare a const of ref equals use ref function use ref returns an object an object that has one property of current if you pass in a value to use ref you can set the property of current to some value I will set the current property of my ref object to be zero then within handle click within handle click I will access my ref object access the current property then I'll have access to that value I will set the current property of ref to be ref. current property plus one or we could use the increment operator every every time we click the button we will increase the current property of ref by one and then I will display what that value is console.log access our ref object access the current property let's go to inspect console our component rendered once every time I click the button our component isn't rendering we've only rendered it once the value stored within the current property of my ref object isn't increasing each time I click the button without the component rendering use ref returns an object an object that has one property a property of current let me show you what would happen if I were to console.log ref my reference so here's ref it's an object it's an object with one property when we create this reference the initial value is going to be the initial value we pass in to use ref zero but if I were to change this let's say that the initial value is pizza ref is an object an object with one property of current the value stored within my current property is a string of pizza so what we'll do in this next demonstration is create an input element but we do need to wrap all this HTML within a single element because we can only return a single element at a time normally so we will enclose all of our HTML within a div so we have a button and an input element the current property of your ref object can also refer to an HTML element and that's where use ref is really helpful your reference should be descriptive of what you're referencing we will reference this input element I will name this reference as input ref I will set the initial value value to be null meaning no value within that HTML element we have to set the ref attribute equal to that reference of input ref the ref attribute of an HTML element it's a special attribute used to create references to elements after our component renders I'm going to console.log input ref we'll take a look at what it contains so here's our input ref object it's an object the property of current is set equal to this input element and this input element is one gigantic HTML object if we make any changes to this HTML element it's not going to cause this component to reender and to even check that I have console.log component rendered within use effect if this component renders we'll console.log this message so what would we like to do when we click the button let's take our object of input ref access the current property that will give me my HTML element my input element I will use the built-in Focus method to give this element Focus if I were to click on this button our input element is going to have focus and it doesn't cause the component to render just to check that let's go to inspect console our component rendered once when we initially mounted it every time I click the button the component isn't rendering which is good we don't necessarily need the component to reender every single time not only that let's change the background color of our text box we can really do anything we want with this HTML element without causing the component to reender Let's access our input ref object access the current property that will give me this HTML element let's access the style property access the background color and set it to be yellow now when I click the button we have focus and the background color changes of this input element let's create a few more HTML elements let's copy this button and this input element paste it twice we'll have clickme one click me2 click me3 we'll have to create a few more references let's copy our current reference paste it twice input ref 1 input ref two input ref three the ref attribute of each input element will be input ref one then input ref two input ref three we'll create two more handle click functions just to keep it simple handle click one handle click two handle click three handle click one handle Click 2 handle click three so we need input ref one input ref two input ref three when we click on one of these buttons the background color is going to change as well as the input element having focus when we click on one of these buttons I need the background color of the other input elements to reset back to normal so really we can just copy what we have for the background color but access input ref two and three set the background color to be an empty string for the default if I were to click on button one input ref one is now yellow when I click on button two the background color is yellow input element 1 and three now use the default color and the same thing goes with input element three if I were again to go to inspect console well our component still only rendered once by interacting with these buttons it doesn't cause the component to reender that's because we're using use ref and not use State you don't need to write all this but I changed my program around so it's using use State rather than use ref every time I click one of these buttons now since we're using use State the component rerun ERS by avoiding rendering when it's not needed it's going to make your component more efficient all right everybody so that is used ref use State renders the component when the state value changes use ref means use reference we're storing a reference to something when you use use ref it returns an object an object with one property of current that current property can store a value an array an object or an HTML element when the stored value changes it doesn't cause the component to render this is helpful with accessing and interacting with dom elements handling Focus animations and transitions as well as managing timers and intervals we'll be working with us ref in the next video where we will be making a stopwatch component and well everybody that is the US ref hook in react what's up everybody in today's video we're going to create a working stopwatch using us react so sit back relax and enjoy the show okay let's get started within our source folder we're going to create a stopwatch component stopwatch and this is going to be a jsx file we will be working with function based components function stopwatch no parameters then be sure to export it export default stopwatch in this program we'll need three different hooks let's import them import from react use object destructuring we'll need the use State hook use effect as well as use ref from its location of react we do need to return something for the time being we're going to return a fragment okay let's import our stopwatch from our app component we will import stopwatch from its location slash of stopwatch jsx we will return a single stopwatch component and that is all we need for the app component within our stopwatch component we'll make a few declarations we'll be using the use State hook as well as the use ref hook we'll need to check to see if our stopwatch is currently running we will use use state const is running and a Setter for or is running equals use State I will set the initial state of is running to be a Boolean of false our stopwatch is not currently running we'll also need to keep track of how much time has he elapsed that will also be a state variable const elapsed time and a Setter for elapsed time again we're going to use you state I will set the initial state of our elapsed time to be zero for 0 milliseconds we'll be working with intervals if we start an interval we need to clear it if we're not using it we will use ref to create a constant of interval ID ref equals use ref we will set the initial value of current to be null when we start our stopwatch we'll have to get the current time we'll store that as a reference using use ref const start time ref equals use ref I will set the initial value to be zero our start time will be 0 milliseconds a few things we'll need we'll need to use the use effect hook we will pass in a function and a dependency array the dependency array is going to have one state variable of is running basically speaking when we Mount our component and if is running ever changes we'll perform some side code whatever is within use effect this is where we'll start our interval to move time forward we'll get back to that later we will create a function to start to start or stopwatch a function to stop a function to reset and a function to format time format time within our return statement let's return all the HTML we'll need for this program I will create a div element to act as a container this div element will have a class name of stopwatch within this div element we will create a nested div element that has a class name of display to display the time when we display the time we will embed some JavaScript and call the format time function within our format time function just so we can display something I'm going to return a template string that displays a bunch of zeros really I'm just using this as a placeholder so we are returning a string of a bunch of zeros we'll have three buttons these three buttons will be within another develop vment this development will have a class name of controls we will create a button that has text of start to start the stopwatch this button will have a class name of start- button with this button we will set the onclick event handler to be a JavaScript function we will pass in call back to the start function to start the stopwatch then we need a button for stop let's copy this button paste it change any instance of start to stop onclick will be a call back to stop the class name will be stop- button the text will be sto then we need to reset button let's copy our button paste it change any instance of stop to reset we will pass in a call back to the reset function the class name will be reset dasb button and the text will be reset and that is all the HTML that we need go to our CSS stylesheet now we'll apply some CSS within the body of our document we'll use flex box to display each component display Flex I will set the flex direction to be a column there's not really be any apparent changes until we add more components then I will align items in the center and set the background color to be light gray but I'll use hsl values I will set the lightness to be 95% okay let's zoom out then I will select the class of stopwatch this class contains our stopwatch everything within it I will again use flex box and really I'll just copy these three properties from the body so display Flex Flex Direction column align item Center I will add a border a 5 pixel solid border radius to smooth the corners a 50 pixels set the background color to be white then add some padding of 30 pixels all right let's work on our display next the text is pretty small we will select the class of display increase the font size to 5 RM set the font family to be monospace or some other font that you like let me Zoom back out I will set the font weight to be bold I'll change the color pick a color for the font color I will set the lightness to be 30% I'll add a text Shadow effect text Shadow 2 pixels by two pixels for the vertical and horizontal offset and a blur radius of two pixels and pick a color I'm just going to lower the Al to 75% just so it's more transparent then add a little bit of margin to the bottom margin bottom 25 pixels okay and that is what we need for our display let's work on our buttons next So within our div element of controls I would like to select all button elements within this class select our class of controls select any buttons within our controls class let's set the font size to be 1.5 RM set the font weight to be bold add some padding of 10 pixels by 20 pixels surround each button with some margin 5 pixels I will set a minimum width of each button to be 125 pixels remove the border with border none use border radius to round the corners 10 pixels when we hover our cursor over a button let's change our cursor to be a pointer and that does work I will set the color the font color to be white we'll change the background color pretty soon we'll also add a transition effect let's select the background color and use use an ease transition after 0.5 seconds we will ease let's select our class of start button class start dash button pick a background color I'll pick something green meaning go cuz we're starting our stopwatch background color green but I'll use hsl values cuz I think they look better I've already pre-picked a color I will select these values for the Hue 115 for the saturation 100% for the lightness 40% let's also access the hover sudo class let's copy and paste our start button access the hover sudo class when we hover our cursor over the button what do we want to do let's take the lightness and subtract 5% 5% from whatever it currently owes I'll set mine to be 35% so the color should get a little bit darker when you hover your cursor over the button let's do this with with our stop button we'll copy and paste what we have for our start button change start to stop I'll make the background color red but I'll select something specific for the Stop button I'll set the Hue to be 10 the saturation to be 90 90% And for the lightness 50% let's copy and paste this background color within the hover sudo class set the lightness to be 5 % darker and that does work now for the reset button let's make it blue change stop to reset and pick a blue color for the Hue I'll select 205 90% for the saturation for the lightness 60% when we hover our cursor over the reset button I will set the lightness to be 5% darker so 55% and that looks pretty good and we can close out of our CSS Styles sheet let's go back to our stopwatch component let's work on the start stop and reset functions when we press the start button we will call this function of start so to start the stopwatch we're going to use the setter for is running and set that to be true we will set the state of is running to be true once we press the start button we want this program to be running we also need to set the start time reference updating a reference doesn't cause our component to render if a state changes it does cause the component to render we're going to set the start time reference this is an object we will access the current property and set it equal to now we need to calculate what the start time is so if we were to get the date right now this is is going to return the current date and time in milliseconds minus the elapse time which is initially zero so just to show you what this looks like I'm going to console.log the current property of my start time reference object if I was to start or stopwatch we be given the current date and time in millisecs since epic think of Epic as when your computer thinks time began it's usually a dat around the year 1970 1.7 trillion milliseconds has passed since epic if I were to start the stopwatch again you can see that this number increased slightly we're converting the current date and time into milliseconds by keeping a reference to when we started the stopwatch we can see how many milliseconds has elapsed since then that's kind of the general idea we can get rid of console.log we don't necessarily need it keep it if you would like to stop the stopwatch we're going to set our Boolean of is running to be false that's all we need to do now for reset we're going to set the elapse time to be zero because we would like to reset everything set the state of elapse time to be zero and we will also set is running to be false set is running false if you would like to stop the stopwatch when you reset set is running to be false then since we have a dependency array when we Mount this component and anytime the state of is running changes we'll perform some side code I think what we'll do first is check to see if is running is true if is running if our stopwatch is now running we'll need to create an interval to move time forward we will use the set interval function this has two arguments a call back to a function and a Time in milliseconds to repeat this interval let's say after every 10 milliseconds we'll perform some code I'll use an arrow function after every 10 milliseconds we will set our elapse time to be a new state we will get the date right now minus whatever our start time was we can use our reference start time ref access the current property remember that was milliseconds so get the time right now subtract what our start time was and that will give us our elapse time because we're using the setter for elapse time in order to clear this interval we'll need to keep track of it by its unique ID the set interval function returns that ID we will take our reference of interval ID ref it is an object we will access its current property and set it equal to that reference we should add a cleanup function to the end of our use effect hook we will return a function a cleanup function when is running changes or we unmount our component what would we like to do we need to stop the interval from continuing if we don't it may lead to unexpected Behavior we will use the clear interval function and pass in that unique ID access the current property of our interval ID reference and clear it that will allow us to clear this interval so our program stops running now we just need to fill in the format time function we have a lapse time it's going to be in milliseconds we need to convert it to hours minutes seconds and milliseconds we'll start with hours let hours equals take our elapse time now to convert milliseconds to hours you can follow this formula take our elapse time which is in milliseconds divided by there's 1,000 milliseconds in a second time 60 seconds in a minute time 60 minutes in an hour and close this equation with the floor method of math math. floor okay let's calculate minutes let's change hours to minutes what we got to do is take 1,00 * 60 modulus 60 mod modulus gives you the remainder of any division once our minutes unit hits 60 we need to reset it back to zero that's why we're adding modulus 60 we don't want it to continue to 60 or something above 60 then we have seconds let seconds equals elapse time divid 1,00 modulus 60 and milliseconds let milliseconds equals our lapse time modulus 1000 if you don't want to display all four digits of milliseconds we can divide this by 10 to display only the first two digits we will return a template string we will display the hours colon placeholder minutes colon placeholder seconds colon placeholder milliseconds now if you don't want to display hours you can remove that I'll only display minutes seconds and milliseconds so here's what's going on currently let me stop it so we can start we can stop and we can reset however I would like to format the time I would like to display a leading zero well we can use the pad start method of strings so let's take ours equals we'll use typ casting to convert ours to a string then follow this with pad start method pad this number with two zero characters let's do this with minutes minutes equals convert minutes to a string and then pad it with two zeros seconds and milliseconds all right let's see if this works we can start we can stop we can start again we can stop again we can reset we can start and we can stop now the cool thing about doing this in react our stop watch is a reusable component if I were to go back to my app component I can include as many stopwatches as I would like let's include one two or even three these are all individual components that have their own code to run they all run independently and I can stop them whenever I would like all right everybody that is how to create a stopwatch component using react