React Beginner Course 2024 (Vite, Tailwind CSS, TypeScript)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome to the 2024 react beginner course in this course you will quickly learn what react is how it works and how you have to think when you build applications with react this is a beginner friendly course we will start simple and then step by step learn more advanced react Concepts and we will even use typescript and tawin CSS which are technologies that are used in many projects these days so you want to hit the ground running and learn how to use them right away if you don't know know what any of this means don't worry you will learn all of this throughout this tutorial we will also learn how to organize our react projects how to split up code into smaller components and even how to create our own custom hooks we will also learn common react mistakes in the process and how to solve them so what are the prerequisites of this tutorial well it would be perfect if you already have some basic knowledge in JavaScript HTML and CSS even if you don't even if you are a complete beginner in web development you might be able to follow along with this tutorial you might need to look up some Basics here and there but you can always use Google for that or fill in the gaps later after you finish the tutorial you don't need any pre- knowledge about react typescript or Tailwind we will learn all of this in this tutorial let's take a quick look at the project we will build here so I think for a beginner there is no point in building large fancy projects with a ton of features because it's important to really understand the basics of react and not just copy a huge project that looks good but in the end teaches you nothing because it's too complicated and the perfect react beginner project is just a simple to-do list app where we can take off to-dos we have some information here on the screen we can delete to-dos and we can add new to-dos and this will teach you so much about how react works so I recommend that you follow along through this whole project and you will learn a ton about react in the process and one more thing before we start I have a free react best practices mini email course this course is the perfect complement for this beginner tutorial I really recommend that you sign up you can find it at coding andf flow.com react bestest practices it's a short email course that will send you a small lesson every day a small video Lesson where you learn one react best practice it's a lot of fun and it's very easy to follow along all right and then let's start learning react so as the IDE and so the software where we write code in we will use vs code which I would say is the most popular code editor for web development it's completely free to use just download it install it and we are good to go next to run a react app we also need node.js installed you can check if node.js is already installed on your system by opening a command line window and typing in note minus V which is short for version and it shows that I have note 20.9 installed if the says node is not recognized or if your version is below 18 then go to nodejs.org and download and install the latest LTS version LTS stands for long-term support it means that this version will get bug fixes and security patches for a few years again we need at least note 18 so it's a good idea to just install the latest LTS version when you build a new react project it's recommended to use some kind of framework because this way you don't have to assemble the whole project manually you don't have to wire up everything yourself now for real production apps I usually use nextjs which is a fullstack react framework that adds a lot of cool features on top of react like an integrated routing system or backend API routes but to learn the basics of react I think this is a bit too much so instead I want to use V which again has the benefit that it assembles the project for us and it just works but at the same time V is more barebones we don't have these ton of features on top of react we basically just have react if you want to learn how to build projects in nextjs you can watch my other tutorials I have a lot on my channel where we build a lot of cool full stack projects but yeah here we will use V and here on its homepage we have this getting started guide where we can find out how we can create such a beat Pro project we actually only have to run a simple command in the command line so what we do is we go to the folder where we want to put this project you can put this on your desktop or in some other folder doesn't matter here we want to open the command line on Windows we can do this by holding shift down right clicking and then we open the powers shell or command window here and here we type in npm which stands for node package manager we have this available because we installed nodejs and then create space beat at latest we confirm this with Y and then we have to do some configuration first we have to give this project a name let's call it 2024 minus react minus beginner the name is up to you we confirm this with enter then we have to select a framework because V actually works with many different Frameworks we of course want to select react as the variant we want to select one of the typescript variants what is typescript well typescript is a superet of JavaScript it's JavaScript but with types added on top the problem with normal Javas script is that it's dynamically typed you can pass any value to any function and you can put any value into any variable this can easily cause bugs and problems especially in larger projects so more most people these days use typescript which makes sure that we can only pass the values that we actually expect for example here we declared that this is an array of to-do objects which has this exact structure here the completed value of our to-do has to be a Boolean if we try to pass a different value like a string this will not compile we cannot even start our app and this is good because this year is most likely a mistake and we don't want to allow this typescript requires us to write a bit more code than in vanilla JavaScript but the safety we get in return is really worth the effort so I recommend that you don't shy away from typescript it makes sense to learn this even as a beginner and other languages like Java or cotlin which many beginners use as their first language also have this strong type system so it's not an advanced topic it's a basic Topic in my opinion so yeah don't put us off don't start with just JavaScript and plan to learn typescript later just learn it right away start with typescript and you will benefit from this greatly in the future we Select typescript Plus s swz s swz is some stuff under the hood which just makes this app a little bit faster you don't have to worry what this means exactly just Select typescript Plus s swz confirm with enter and as you saw in a split second this new project was created now we can actually close the command line and here is our new project folder we open this in the S code by right clicking open with code if you don't have this option you can also open the es Cod directly go up here to file open folder and open the project folder this way yeah and just like this we have a react project ready to run as you can see it created quite a few files with configuration for us everything in the srz folder is our react application code and the other files outside of of the srz folder are configuration and later when we compile this project this will also be optimized and fast and this is what a framework like V does for us so what we do now is we open the terminal you can find the command for this here in viewer and terminal I use this shortcut control ER then we run npmi or npm install and PMI is the short version of it this installs some packages that are listed here in this package.json this contains react some typescript stuff and some other configuration with npmi we install all of these packages after this is done we go into the command line again and run our project in development mode with npm runev which gives us a URL that we can open yeah and when you go to this Local Host URL you find this template here which has this fancy button that we can click and we want to replace this for our own app we will start writing code in a moment but let's take a look at some files here we have this index HTML which is basically the page that we just saw which contains the HTML tag a head tag with some metadata and the interesting part is the body with this root tag here as we can see this executes this main TSX which is another file in our project and pay attention to this idea it's called root and in this main TSX file we have this script that searches for this root element in our index HTML and here it renders our react app and react by default creates a single page application so we only have this one element here this react page so to speak now when something on our screen changes for example we navigate to a different page via a router then we actually still see the same page it's still our index HTML which renders our react app just that whatever we put inside this app component here changes this is different from a classic website where we make a request to the server we get a page back and we show this page on the screen here we basically only make one request to the server we get this one page back and then everything that happens afterwards is handled by Java script JavaScript replaces the content on the screen and we can actually see this by opening this page again we can open the Chrome def tools with F12 and here we press control shift p search for disabled JavaScript keep the dev tools open but refresh the page with F5 and as we can see we see nothing why because now without JavaScript we don't run our main script and we don't put any react component on on the screen so by default a react app doesn't work without JavaScript which is one of the downsides this is one of the problems that a framework like nextjs solves it brings serers side rendering back into react so that we get the best of both words again you can learn nextjs through my other tutorials but I would recommend that you watch this beginner tutorial first to learn the basics of react and then I think it's a good idea to switch to something like nextjs if we close the command line and refresh the page again we have JavaScript enabled again and the page works again yeah in case you're wondering where this code here is hidden it's in the app. TSX file here is this counter you don't have to understand what US state means for now we will learn this later and here's the button that changes this counter react uses a so-called declarative UI approach whereas a normal JavaScript application uses an imperative approach let me quickly explain what the difference between these two approaches is because you need to understand this in order to understand react so in a normal web app without without any fancy Frameworks your code would look something like this we have an HTML file where we have our different HTML elements for example in there can be a button which shows the current count of our counter this is what we saw a moment ago just how it would be written in a vanilla JS app then separately we have a Javascript file which can execute code which actually brings life into these static HTML files because HTML by itself doesn't do anything besides rendering data on the screen text and images we need a JS file for all the logic and this JS file would look something like this it would have this count variable it would find the button for example via its ID which we said here it would add an event listener to this button listen for the click event and every time we click this button it would increment the count and then update the text of this button this approach is called imperative because we have to explain every step along the way of what we want to do we have to find the button first we have to add The Listener we have to increment the count and we have to specifically update the text content otherwise the text here will not change and not reflect the latest value of this variable so we have to explain every step along the way this is the declarative approach that react uses this is the code that we just saw in the ftsx file just with some of the uninteresting stuff Stripped Away there we don't have separate HTML and JavaScript files there we put all of this into a single file with the file ending either jsx or TSX TSX is for typescript and declarative means we don't explain all the steps that we want to execute instead we only declare what we want to show on the screen and the rest happens automatically under the hood so here we don't say updates the text content after our counter has incremented instead we render the count value down here between these parentheses and whenever the count State changes this will automatically be updated and show the latest value and this makes it much less likely that we add UI bucks to our app because in the imperative approach we always have to remember to do this and this is a simple case what if we want to change more info on the screen we always have to remember to update the actual content of these elements whereas in the declarative approach we just declare what we want to show and then this will automatically always show the latest value which is super cool and react does this by just redrawing the whole screen whenever any of the state here changes this sounds very inefficient but react does it in an efficient way by optimizing the updates under the hood so after we incremented this counter react just redraws the screen with the lat latest value of the count in this button but we don't notice this because this happens in an efficient way another benefit of this jsx syntax is that we can create encapsulated reusable components that contain both the markup the logic and with Tailwind also The Styling instead of having to jump between a lot of different files we have everything that belongs together in a single file and at the same time it makes it easier to organize our code one of the cool things about V is and also nextjs by the way when we change something here for example let's change the text of this button and we save it while development mode is still running we see the changes here immediately and we even keep our state of 11 clicks now just one more step before we can start hacking away we still have to set up Tailwind but this is pretty easy okay so the way CSS usually works is that we set a class on an element for example on this image we have this logo class and this react class the only difference is that in react we set this via this class name argument whereas in normal HTML this is just called class we can't use class here because class is a reserved keyword in JavaScript and jsx and TSX files are basically JavaScript files so this is why it's called class name here just one thing you have to keep in mind and then we have separate CSS files for example this app. CSS s which has selectors for these classes and then it Styles these arguments with CSS attributes so if I want to change the styling here I have to change these attributes in the CSS file TN CSS Works a little bit different there we don't have the separate CSS files anymore instead we have a ton of different utility classes which all fulfill a specific role if we want to make the text bigger we have classes like text LG if we want to add padding margin or a specific width we have separate classes for that with different number values the benefit of this approach is that we don't have to leave our TSX files anymore we can do all the styling directly inside with these different utility classes now most people love Tailwind because they find it makes them more efficient a few people hate it but it's good to learn it because it's a required skill these days in the docks we can find some instructions on how to set this up somewhere here is actually a guide specifically for V so let's search for V and open this page and then we have a few steps that we have to do we have already created our V project next we have to install some packages so we copy this line here go back into our project open the command line again we stop our app that we have running in Death Mode right now with control Z here we confirm this with a wire and then we install these packages with this command we just copied npm install Das casd TN CSS post CSS and auto prefixer and this puts this new packages into the package.json file so after this is done we can find them in here let's go back to the installation instructions next we have to execute this command npx TN CSS in it minus P so let's do this as well in the command line which creates new files in our project tnd config and post CSS config let's take a look into them tnd config which is here in the root of our project yeah and as the name implies here you can do a configuration you can extend the default classes you can add some default styling and some other configuration and here we also have to copy some stuff in which is the third step in the Tailwind documentation we have to copy this part here into the content block of our Tailwind configuration so right here into this array this makes sure that Tailwind Works in our index HTML file and in all our JavaScript typescript and jsx and TSX files then let's save these changes with controls then we go into our index CSS file which basically contains the default styling of our whole website like how links are rendered what margins we have applied by default how headlines look and so on but now that we use Tailwind all of this doesn't have any meaning for us because in tnd all these components are unstyled by default and we style them in the places where we use them with these utility classes so we delete everything out of this file and instead that we have to add these three lines here which wire up Tailwind with our project yeah and now we are ready to use the Tailwind utility classes but you also want to configure your vs code properly to work with Tailwind otherwise this would be a nightmare because we have to make sure that we have proper Auto completion so what we do is we go to this extensions Tab and then you should install the official twin CSS intelligence extension as you can see from the screen screenshot here this will later give us Auto completion inside class name strings with the different classes aailable and this is extremely useful so go ahead install this and then we want to open the settings of vs code search for file associations and here you want to add this file association with the key asterisk docss and the value twin CSS as one word or lowercase this makes sure that twin CSS Works inside CSS files like our index CSS and then we also have to change another setting we search for editor quick suggestions and here you want to turn this on for Strings this way we get immediate autocomplete inside class name strings otherwise you have to trigger this manually which is not very convenient okay lastly I recommend that you also install the eslint extension if you have haven't yet beat automatically has esent configured it's a tool that helps you find problems in your code normally you have to execute this via the command line but with this extension we see these warnings and errors directly inside our editor which is more convenient okay cool let's close all of this let's go into our Explorer here and delete the whole app.css file because now we do styling via our Tailwind classes which also means in the app TSX file this import here is invalid let's remove it because this file doesn't exist anymore and now of course when we run our app in development mode again with npm run def it's all unstyled because we removed the CSS it's interesting to note that almost no element has any default styling in tnd by default so headlines for example or buttons normally have some default styling in CSS but Tailwind removes this default styling because usually it's not what you want we can see the default styling by going into the index CSS F once again and just for a moment comment out this Tailwind base directive now we have the default HTML styling again which looks like 1990 so before our eyes bleed let's quickly put this back in and then we style this stuff ourselves so as you can see here this page is a JavaScript function with functions we create component components in react which are parts of our UI a component can be a whole page like in this case or a smaller element we will create more separate components later above the return statement up here we can put Javascript logic and in the return statement we have these different HTML Texs and whatever we return here is what we render on the screen for this component so let's remove everything inside this return block including these empty tags here and instead put a main tag in here in this main tag we put an H1 headline which will say your to-do because you buil it to do app and then let's remove all this unused stuff we don't need this state for now and we can get rid of all these import statements yeah and now we have our headline here completely unstyled by default now let's style this we do this by adding class names first to the main tag with py10 we can add some ver itical padding with this value of 2.5 Ram we can see this when we hover over it because we installed the Tailwind extension and when we save this our main tag has some vertical padding and we didn't have to go into a separate CSS file and if we want to change the padding we can add a different value like py8 for example without leaving this file Now by default this main tag is only as big as the content in it I want to make this as as big as the screen so we add this Edge screen class and these classes are all provided by a Tailwind they have a ton of these classes as you can see now this takes up the full height of the screen and I want to remove this background color again and in the same way we have to style our H1 headline I want to make this text bold which we can do with font bold and voila we can also make it bigger with text 3XL for example or a different size value and we can Center it on the screen with text Center yeah and this is the whole Magic behind Tailwind now before we continue building the rest of our app I want to add one more package so once again let's open the terminal stop the execution with contrl z and then we npmi which is short for install another package called l react make sure to spell this correctly this is simply an icon package because we need some different icons later and I want to keep the dependencies as minimal as possible in this tutorial let's run this again with npm run Dev which also means we have to refresh the page and again lit react was added to the dependencies Block in the dependencies block are all the packages that we need in production and in the dep depend dependencies block are all the packages that we only need in development when we later compile our project we don't include these dependencies because we don't actually need them to run the app we only need them to write the app like our es L helper or typescript itself okay cool now let's continue building our app okay I want to render a list of to-dos on the screen for this I want to put some dummy data into a file how you structure your project in react is up to personal preference but everything that we use directly in our app goes into the srz folder in here let's create a new file then we write data slash this way we create a folder but in a single operation and here let's put a Todo do TS not TSX this time just TS because this is a plain typescript file and here I put an array that looks like this please pause the video and type this out by hand those are just three dummy to-dos that we want to render on the screen for now later we can add our own to-dos but for now we use this hardcoded data now typescript can automatically infer the type of this array just by the data we put in there it sees okay every item in here has an ID which is a number a title that's a string and a completed value that's a Boolean so when we hover over dummy data we can see ID number title string completed Boolean the problem with inferring the type like this is that this doesn't protect us from accidentally passing the wrong data so as I showed you earlier if I now pass a string here then the type of completed is inferred as either a Boolean or a string which is not what we want we want type safety here we want typescript to protect us from these mistakes so we want to set the type explicitly we could declare this type in here but let's put it into a separate file again where you put it exactly is up to personal preference I I again want to create a new file in the srz folder this time we create this types folder and in here we put a to do. TS and to create a new type we want to export a new interface we export it here because we want to use it inside different files throughout our project let's call this interface to do and then we make a pair of curly bracers and then we declare how this interface or this type should look we use the same structure that we just saw a moment ago we want every Tod doer to have an idea of type number a title of type string and a completed value which is a Boolean we saved this now we can use this type here by going behind the variable name dumy data weite colum to-do which Imports this to-do interface from this file and then we want to make this an array with square brackets and now the difference is that we can't pass the wrong value anymore because now we get an error and this wouldn't even compile and the same is the case for tyos and similarly when we later have function arguments then we also have types there so that we can't pass the wrong data type to a function which is very useful and protect Arron box so let's save this file and go back into our app. TSX file okay below our H1 inside the main tag I want to put a div and in this div we put another div because later we put some more elements in here and we want to separate them properly and in here we want to render our list our dummy data but how do we do this we can write JavaScript code directly in our return block of our J X Files by adding a pair of curly braces this is basically a window from HTML into JavaScript and in here we can put Javascript logic however whatever we put in here has to return a jsx element so either a component or one of these HTML tags and render it here so it has to be an expression so to show you how this works we write dummy data which Imports our dummy data array from our data folder on this recal do map make a pair of parentheses in here we write to do and then we make such a right arrow with an equal sign and a greater than symbol then we make another pair of parentheses because here we want to return something we want to return an HTML element to render such a to-do this way we take this whole array and we say we want to take each to-do in this dummy data so each of these objects and turn it into a UI element this way we create lists in react so whatever we put in here will be rendered on the screen three times for our three to-dos for now let's keep it simple let's just render a paragraph tag which contains the title of each to-do so again we add curly bracers and write too. title and when we save this there are the three titles of our three to-dos now every time you render a list in react like this you have to give each of these list items a unique key this key is important if the order of your items can change because this TS react which item is which so it doesn't update the wrong one later so we need a key that uniquely identifies each item this is what we have this ID for which is unique for each element and in a real application where you store your data in a database you also have a unique idea because every database has a unique idea for all of its rows so the idea is usually what you want to use as the key for your map cards for your lists so here we pass to do. ID and by the way if we don't add this then react will also complain in the console each child in list should have a unique key so don't ignore this and now we also want to style this a little bit we can add a class name directly to each paragraph tag make the text a bit bigger with text LG then I want to add some vertical spacing between these elements so we go inside this inner diff here that surrounds our list and here we add the class space Y2 and again you can always see what CSS values this applies by hovering over these class names and to the outer diff we add the class names Max wlg and MX Auto which gives this outer wrapper a Max width and zeners it on the screen so that it doesn't go all the way to the edges of the screen cool it's also worth pointing out that we can't put a for Loop down here into these JS Expressions so we can't do something like this this will not compile because a for Loop is not an expression it doesn't return something and we can't return a UI element from a for Loop whereas the map function is an expression it returns whatever we returned from its block and this is what in the entry put into the UI but you can't do this with a for Loop you can put for Loops above the return statement up here but not inside a return statement okay next we want to add some more styling to our list items to make them look like actual to-do list items and in the process we will create our first own component as I touched on before with comp components we can create encapsulated reusable parts of UI that can even contain their own logic this way we can organize our code and we can make parts of the UI reusable for example we might want to show our to-do list on different pages not only this app page here by putting it into a separate component we don't have to repeat the exact same code in all these different pages these days in react we write components as functions in the past we wrote them as as classes but those were the olden days where dinosaurs were still alive and we still had faros these days we write our components as functions okay let's do this let's create a separate component for our to-do items here so we open our Explorer again and I want to put this into srz then a folder called components and in here too item or Tod do a list item or to- do row whatever name you you want to give it and this has to be a TSX file this time because it's a component right and here we export a default function with the same name to-do item and the naming convention for components is Pascal case so camel case but with an uppercase first letter whereas normal html text start with a lowercase letter components start with an uppercase letter you don't have to follow this naming convention in the file name you could also give this a different name like to do minus item in our lower case but I prefer giving the file and the default export component the same name in this case to-do item and this is a function so we add parentheses and a block of curly braces remember in a component we have to return a piece of UI so let's return parentheses the parentheses are only there so that we can put the return code into a new new line and for now let's just return an HTML div which just says to-do item just for now so that we can put it on the screen then we go back into our app. TSX file and instead of this paragraph tag we render such a to-do item which we do in a similar way how we render an HTML tag just that this starts with an uppercase first letter so the name of the component and we give it as self closing tag and when we save this we should see our to-do item div three times on the screen because this is the layout we hardcoded in here but of course we don't want to hard code to-do item three times we want to render the data of each to-do item so how do we get this to do a typescript object into this component for this our component has to accept props props are just function arguments to react components now in the Wild West that is vanilla JavaScript we could just declare these props here without any types and then pass them but in typescript we have to prepare a type for our props again we do this with an interface we could put it into a separate file but for organization it makes sense to put it into the same file as the component that uses it the name of this interface is up to you I usually call it the name of the component and then props appended to it C Braes and here we declare what arguments this component should accept we wanted to accept one of these to-do items which we import from our types folder then down here in the parentheses we get past the props which has this variable name props and we can say this is of type too item props and now when we save this and we trigger autocomplete here with control space we see that this now accepts this one argument to do and to this we can pass the to-do variable of this map call and now we can use this data in our to-do item component what we can also do is we can destructure these props so we remove this variable name and instead add a pair of curly braces and in here is our to-do item because it's part of the props and now just like before instead of to-do item we can render curly braces to-do do title and see it on the screen so this is how props work in react with typescript pretty simple huh but I want to style this a little bit more like actual to-do items so let's actually remove this to-do do title here and instead let's put a label in here I use a label because I want to put a checkbox in here and I want to check this checkbox even if we click not directly on the box but anywhere else on this item and this is what an HTML label achieves this is not specific to react this is HTML itself okay in here we want to put a checkbox which we do with an HTML input element which gets a self closing tag we set the type of this input to checkbox and those are basically props the same way how our to-do item also accepts props those are arguments to these different components or HTML elements so when we save this we see three check boxes let's also make them a bit bigger for which we have this tent class called scale and we want to scale this to 125% just to make them a bit bigger okay cool and still inside the label below the input we put a span with the text of the to-do the title so here we render too. title and again we want to style this ban now here's a cool thing we don't have to hardcode these class names instead of quotes we can also put an expression here in curly Braes and here again we can put Javascript Logic for example we can use a Turner operator we can say okay if Todo completed is true and we use the Turner operator with a question mark then we want to return a few classes and if not colum we don't want to apply these classes so we keep this class name String empty and only add some styling here which will only be applied if completed is true if completed is true I want to make this text struck through so I want to add this line through Tailwind class and I want to make the text Gray with text Gray 400 and as you can see we even get a color preview because we installed the Tailwind extension so now we have this conditional class here to see this in action let's go into our array here our dummy data and let's just set the completed value of one of these elements to true and now it's rendered in this different style isn't this cool we also have to style the label itself a little bit with some class names we make this a flex box with flex we want to Center the items with item Center we give it a gap of two I think most of these class names are self explaining we want to add a border we want to make this border rounded with rounded MD when you have a border you usually also one add some padding with P minus 2 and I want to change the color of the border with border gray 4 100 of course you can style this in any way you want we want to set the background color of each element to White and one more we use this hover modifier this way we can apply a class only when we hover over this element with the mouse I want to change the background color to BG slate 50 here so type all of these classes out and then our elements look like this and when we hover over them we have this color change and the benefit of using a label is that we can now click anywhere on this item to check the checkbox because all of this is the label which is connected to the checkbox inside it yeah and because of reacts declarative approach we didn't have to change the styling of this last element here explicitly we didn't have to give our code instruction and say change the background color of the text to this color and so on we only declared how we want our items to look depending on the data that we pass in and when the data that we pass in changes the screen automatically rerenders with the new UI State okay a little bit more styling I want to add to the app page itself first of all I want to have some spacing between the headline and the list so we go to the main tag and add this space y5 class which adds some vertical spacing then we go into the diff that has this LG Max width here I want to set the background color to BG slate 100 again I want to make this rounded and add a petting of five and now it looks like this really cool okay but we are not done yet because right now now when we check one of these elements even though the checkbox changes of course this doesn't change any of this data in our array here when we refresh the page all the checkboxes are unchecked again so we don't store the state anywhere react follows this idea of unidirectional data flow which sounds very boring but stick with me for a minute it's important that you understand this unidirectional means that our data only flows downwards we have state in component and we can pass this state down to smaller components via props as we just saw a moment ago because we passed our to-do State down to the to-do item which is a separate component if this data changes as result when we change the Boolean value here in our array this part of the component tree that uses this data is rendered by react to represent the new state so the styling of our to-do items here changed this means we keep the state of each part of our component Tre in the parent of all these different components so let's say the first one here at the top is our app page this one here is our to-do item and let's say in some other component for example a statistics element we also need our to-do list then we keep the to-do list in the parent which is the page itself and we pass it down as props to the child components that need this State we could not put this to-do item State into the to-do item component for example because then we can't access it in the parent and then the other child component can't access it it has to be in a common parent and usually you put it in the lowest common parent where you need this date if this is still confusing to you don't worry you will get the hang of it as we continue building our project but sometimes of course we want to update this date from a child component for example when we check a to-do list item which happens here in this child component we have to change the state of the to-do list itself and we do this via callback functions so let's see how we can Implement such a callback function in our project so we go into our to-do item component file and we add a new prop again the name of this prop is up to personal preference I'm going to call it uncompleted change colum and the type of this will be a function which we declare like this parentheses right arrow and the return type which is void it doesn't return anything however this function takes arguments it takes the information we need when we check an item in our to-do list when we check an item what information do we have to pass to the parent to change the state well we need to know which item we checked which we can figure out by the idea and the newer checked state if it's checked or not so we add these two values as arguments to this function the ID which is a number and completed which is a Boolean but we don't need the title of the to-do item to change the state we only need the idea and a new completed value then we destructure this new prop down here on completed change then we go into our check box here let's put this over multiple lines and add new props first of all I want to say this checkbox should only be checked if the to-do item is actually completed because right now this doesn't actually reflect the completed value in our array so even though this is struck through the checkbox is unchecked by default we can fix this by setting the checked value explicitly to an expression we set this to to do do completed now this is checked and we can't change the checked State anymore we will fix this in a moment and then we want to implement our callback for this we use the onchange prop which will be executed when we click such an item in here we pass an aror function which receives this argument e and when we hover over it we can see that this is of type react change event this is what we get passed when we click one of these checkboxes we want to call our uncompleted change callback which remember expects the to-do idea and the new completed value for the ID we pass to-do do ID that's the item we clicked comma and the new checked value is inside this e variable e. Target do checked okay and now every time we click a checkbox we trigger this callback but what happens with this callback right now we don't do anything with it right now since it's a prop we have to now pass it to our to-do item component here's our uncompleted change CAG and in here we can do something with this CAG we could pass this as an error function like this but for organization you often want to declare a separate function for it which you can do above the return statement inside the component here let's put a function called Z to do completed again the name is up to us and this has to take the same arguments as our callback so let's actually copy these put them here between parentheses curly braces and now we can pass this function name down here as the prop value but pay attention we don't call this with parentheses we just pass the name this way we pass a function reference we call set to- do completed whenever this callback is traed now we don't have any state that we can update yet we will learn about this in the next section for now let's just show an alert message so that we can see that we actually received this call back so we call alert we pass a back Tex string here because this way we can put variable values inside the string and let's write to do with idea dollar sign curly Braes idea is now dollar sign curly braces if completed is true it should say is now completed and if not it should say not completed so just type out this string and if you paid close attention you might have noticed that I forgot to set the key here if you notice this then good job the key is necessary whenever we render a list so again let's pass to do. ID here and then let's see if our callback works so we save everything open our page and now when we click an item we will see the new state to do with ID one is now completed we don't see it on the screen yet because we don't actually change any state but we can already see that this works so next we will learn about react State and how we can actually change what is shown on the screen when we click one of these to-do items so right now all our to-dos are hard CED into this array how do we make it so that we actually have state that we can change when we click these to-dos for this we need react State and we created the following way we go at the top of our app component inside the function we declare a const and then we make a pair of square brackets like this and in here we write todos and Z to do in chem case like this equal assign and we assign this to use state which is an import from react can see it up here if it didn't import automatically write this out by hand and to use State we pass our dumi data yeah and from use State we get these two values inside this tub inside this array the first value is this state itself which as you can see is of type to do array because this is automatically inferred from the dummy data that we pass here which is the initial value this state will have when we open the app if we didn't pass a default value here then the type of the state is undefined but types script can infer this type we could also set it explicitly in angle brackets like this but it's not necessary the second value we get here set Tod do is a function that we can use to then update the State more on this in a moment and all these functions that start with the word use are special functions called hooks in react hooks allow us to use special features in react like state or side effects more on this later and we will even create our very own custom hook at the end of this tutorial so stay tuned so now instead of showing this alert message here we want to update our state when we check or uncheck a Todo so we call our Z Todo function which is this one here the state updator this function has two versions we can even pass a new state directly by its value for example we could pass an array with to-do objects the other option is to pass an error function in here so parentheses here we get pass the previous to-do so this is the state to-do has before we updated and we can use this to create our new state with this arror function whatever we return from this error function will be the new state of too what do we have to pass here where we have to pass an array similar to our dummy data but with the updated State how do we do this we do this by taking the pref to do which contains the Old State and we map this to our new state map is a function that you use very often in react because it really fits to this functional nature of react it's how you transform an array into a different array so for organization let's pull this into a separate line here we call map as usual when we map our array we get past each item in this array in an arrow function so again we make a right arrow and what do we want to do in this map call well we want to take our old State we want to find the element that has the idea that we just clicked in our UI and we want to update this element to have the new updated complete deleted state so in here in this map arror function we make another pair of parentheses and then we put an expression we check if to- do. ID of this iteration in the map call is the same as the ID that we pass here then we know that this is the item we want to update so we use the Turner operator and we pass the new state of this to-do so we pass a JavaScript object we spread the exist thing to do from the map call with the title and the IDE but after a comma we want to update the completed value to this newer completed value so we only update this one field if the IDS don't match then this is not the object we want to update this is one of the other objects in the array in this case colon we just want to keep the old Tod do with the old State and even though this looks a bit complicated this is how you up update state in react now this is more complex because we are updating an array if the state was just a normous string then of course this is simpler but here we have to map this array to the new state and we can see that this works by replacing our dummy data down here for our to-do state which should now be able to actually update let's try this out let's click an item and as you can see now this state changes isn't this cool now it's important to note that map returns a completely new array when we hover over it we can see call A Defined callback function for each element and returns an array that contains the results so map does not modify the original array it returns a completely new array and this is important because the way a react notices that it has to update the screen is by comparing the references of the state so when it notices that we replaced our array in this to-do state for for a new one the new array will have a new reference different from the old one and this R react knows that it has to reender the screen with the new data this is why we can't modify the existing array directly then we won't get our state update let's try this out just for a moment I copied this map call but I remove the Z too and here I try to modify to to doce array directly but now when we click something the state doesn't change why because the array inside the to-do State still has the same reference as before it's still the same array just that we modified it so react doesn't know that it has to update the screen we always do this via this state sets now of course by default this state is only saved in memory so when we check these values here and we refresh the page it set back to the default State again later we will learn how to persist these values for now I I want to reset this back here to false by default and when we refresh the page all items are unchecked by default and next I want to add a form to add new to-dos to our to-do list okay I want to put the form to add a new to-do above to Todo list here now we could put this directly into our ftsx file right here above this div but for organization it makes sense to put it into a separate file as a separate component especially since this input form will also have its own State and some logic and extracting this into a separate component is really nice for organization so let's put a new file into our components folder called add too form. TSX again we export a default function with the same name which returns some UI so we add a return block here I want to return an HTML form in which we can put an input Field opening angle bracket input self closing tag for now let's save this and put this into our layout so Above This diff here that wraps our list let's put our new add to-do form component and there it is just completely unstyled by default because we use tailwind and let's also add some spacing here so to the diff above we pass another class space y 6 now we have some spacing now let's finish styling our add to-do form component so we can add a placeholder to this input field with some text that will be shown when we haven't typed anything in yet what needs to be done question mark there it is we can can also style this input with TN classes I want to make this rounded but only on the left side so we use rounded SMD s stands for start which is the left side the reason I want to make this rounded only on the left is because I want to attach a button here on the right side so we don't want rounded corners on the right then we make the form itself a flex box and add the grow class to the input field so it grows to the full available width then we give this a border we change the Border color to gray 400 again and add a padding of two so now this already looks much better as I said next to it still inside the form but below the input tag we put an HTML button and the text will say add there it is unstyled as usual we set the type of this button to submit because we are inside a form this way when we click this button it will submit the form and later we will decide what we do when this happens and then of course we need to style this button I want to give this button a fixed width of W6 I want to make it rounded but this time only the right side surrounded EMD e stands for end I want to set the background color to BG slate 900 which is not quite black and we want to set the text to White and then I want to change the background color when we hover over this button so again we use this hover modifier hover colon and when we hover over this button we want to set the background color to BG slate 800 now now we have this light hover effect Now by default input fields in react have their own internal State this is why we can type something in here even though there is no use State for the input here in our component this is possible because these input Fields have an internal state which is handled by the Dom so the the HTML tree itself basically and in react you have two options you can either keep it like this and then just get the value out of here when you need it or you can turn this uncontrolled field into a controlled field controlled is what we did earlier in our to-do item where we pass the value for this input field directly and then we have to update it via a callback these controlled input Fields give you more control no pun intended over what you do with this input for example after we added a new to-do I want to make the input field emptier with an uncontrolled input this is difficult with a control World input that is backed by a state that's easy because then we can just update a state so let's turn our input field into a controlled input field for this we create a new state at the top of our add to-do form component we have already done this before we create a const with scrap records we assign this to use State and as the default value this time we pass an empty string here again we have our state which we call input and and we call the Zeta Z input again the type is inferred to a string because of the default value and now we turn our input field into a controlled input field by setting the value to our input when we save it like this and we put a cursor in here and type we can't type letters in there anymore because now we overwrite this internal state and instead reset a state explicitly and this state at the moment is always an empty string we never update this this is why we can't type anything in here we change the state again via the onchange prop where again we get past this react event which contains the current input and here we can call our state Setter we could put this into a separate function but since this is just one line of code we can write it as an inline function like this and here we get the new input value again from e. target. value and now we can type something into our input field again but now this state is stored in this input State variable which gives us more control over it and now we only want to do something when we submit our form right let's put this into a separate function for organization let's call it handle submit and when we click our button here which is of type submit this form will be submitted and we can decide what we want to do in this case by passing this onsubmit function for which again we want to pass a reference to our handle submit function now this onsubmit function passes an event to the handle submit function but since we declared as a separate function we also have to set the type of this argument explicitly this is not inferred to find out what this type is just for a moment let's remove the handle submit down here and pass an error function nvs codes tool tip tells us what argument this expects it's an event of type react form event of type HTML form element so we can pass handle submit again and use this type up here so again react dot form event angle brackets HTML form element and we need this evalue here to call e. prevent default by default when you submit in HTML form it will send a post request and refresh the page this is the default behavior in HTML in react you often want to handle forms differently you want to handle them with JavaScript code via this onsubmit function and to avoid that the page refreshes we have to call e. prevent default but the rest is all handled by our input state first of all I only want to add a new to-do if the input field is not empty right so we check if exclamation mark input. trim which we call as a function trim removes any white spaces at the end and start of each line so that we can't just pass a string of empty white spaces this still counts as no input in this case we just want to return from this function and not do anything else if we submit a valid input what do we we want to do well we want to pass this input to the parent that uses this form why because our to-do list State lives in the parent component not in the form itself here is where we have to update it we already know how to do this via a callback so we create a new interface add to-do form props above the component function itself and here we pass this onsubmit callback function which will receive the title of the new to-do as an argument and not return anything so we declare this function argument and then we destructure these props down here curly bracers add to-do form props and in here we find our onsubmit function then down here still inside Handel submit we call our unsubmit callback pass the current input state which is stored in use State and always contains the latest input value and one more step I also want to set the input back to an empty string remember this is why we stored the input in the state in the first place because this way we get more control over it and we can do stuff like setting it to an empty State again so let's save this and then pass this call back here in the add to-do form onsubmit here we will call add to-do which is a function that we now have to create let's put it below set too completed and later we will better organize these functions here but for now we just keep them in this one file here we get past the title in form of a string and then we want to create a new to-do and put it into our to-dos array again we can't modify the existing state then our state update will not work we can just call to too. push instead we have to call set to-dos and pass a completely new array with a new reference that contains the new to-do inside it so again we use this function where we get past the pref to-do we pass an error function this time we don't call do map but we still need to return an array here so we create an array literal in this array we want to put our new to-do object so we create an object with cly Braes we get autocomplete here because the type of our state is to-do array we set the idea to the ID of the last item plus one now if you use a database this is handled automatically for you but here we don't have a database so we do this ourselves so we take the length of bre to do and just add plus one the title is the input from the input field and reset completed to fals by default and then after this object here we also want to put our pref to-dos in here which we do with the spread operator three dots because this is a completely new array right and we still want to have all the existing to- in here plus our new one which will be added at the top of the array if you want to add the new item at the bottom of our list then you have to put it after PR Tod do in this array yeah and now when we save this this should work and just like this we can add new to-dos nice now before we continue here is a little quiz for you you know how we can update new to-dos to our state and how we can update our existing state based on the information and everything you learned think about how you would delete an item from our to-do list how would you update the state to remove move an element remember that we have to pass a completely new array now before you continue watching this video please take a moment think about this and then write a comment on this video with your solution and I really recommend that you do this exercise because it will help you cement your knowledge and think in react don't worry if you get it wrong I will tell you the solution in a moment it's not easy but if you try to come up with something yourself it will really help your learning process so leave your solution in the comment below the video and then let's continue by adding a delete functionality and a sorting mechanism to our to-do list so I want to sort this to-dos array I want to put the completed to-dos at the bottom of our list again we could put the Sorting logic directly into our app component but then we would have a lot of stuff in this component so it makes sense to extract this into a separate component for organization in fact I want to take this whole diff that renders our to-do list cut this out and put this into a separate component again in the components folder let's call this to-do list. TSX export default function as usual with the same name and we want to return this diff we just cut out of course we need some props and we also have to import this to-do item here then let's go above the function declare a new interface Todo list props what do we need well we need the to-do themselves and we also need a callback for uncompleted change because the state still lives inside the app component and we have to pass the state all the way up to the parent the reason why we don't move the to-do list State into this component here is is because later we will also have a third component below our to-do list which also needs to to-do State and remember from the graphic earlier we always want to keep the state in the parent of these components that use this state so let's add these props to our interface to-do is of type to-do array again we have to import the type an uncompleted change which will have the same type as in the to-do item component we just forward this whole function and also a third one we also want to be able to delete to do is through this list later we call it on delete and here we only need the idea of the item we want to delete to remove it from our state let's destructure these props down here again this is of type to-do list props and in here we have to-do us on completed change and on delete so we still render our to-do items here just that for uncompleted change we now have to pass the function with the same name to pass this to the parent let's go into the app. TSX file render this to-do list here which expects the Todo which is the Todo State and for the uncompleted change we pass our set to do this completed callback function so this still works the same just that now we have to pass it through one more level we have to pass this callback from the page to the to-do list to the to-do item where this callback is then triggered this is called prop trilling passing props through multiple layers of course at a certain point this can become too tedious if we have to pass this through multiple layers there are solutions for this like react context which we use in my more advanced tutorials but for now prop drilling is fine we will take care of on delete in a moment for now I want to sort this list we can do this above the return statement of the to-do list component here we create a const that we call to-do is sorted we take our to-do is state which we get passed as a prop and Rec call. sort on it to a sort we pass an error function which gets pass two arguments which are two to-dos which are often just called A and B and we can use a and b to sort our list in here we write if a do completed is equal to B do completed cly Braes then we want to return b. IDE minus a. idea oops a. idea because from the sort function we have to return a number and this number decides the order in which these elements are put you don't have to understand this logic here in detail I will show you in a moment how this will sort our elements below this if block still inside the sort function we return a do completed question mark one colon minus one and here you can also see why I wanted to put this into a separate component because if we put all of this stuff into our app component it becomes very hard to read and unorganized really quickly so by putting this into a separate to-do list component we keep this logic encapsulated and are reusable because we can put the same to-do list into another page without having to repeat this code okay cool and now instead of run rendering the to-dos here we simply use to-dos sorted and after we save this our toos are sorted again the Sorting logic is in here and what this does is it puts all the done to-dos at the bottom but when we uncheck them they get put back up into our list of course you can customize the Sorting logic if you want but I think this is pretty cool now here's an important thing to understand about react every time a component is rendered the body of this function is executed again which means that when our to-do state for example changes or any of the other props or state it runs this code again this is why it's important that you don't put any side effects like database operations directly into the body of your components because then this will execute villy when we reender our component which is never what you want we will later learn how we can can still execute side effects in a more structured manner but putting our Zord function in here is fine because this doesn't have any side effects it just sorts this array and stores the value in a variable now you might be wondering isn't it expensive to execute the Zord function every time we reender our component which can happen quite often and that's a good point but calling Zord on an array like this is an extremely cheap operation it's very fast so it's okay to execute this on every render if to-do was a very huge array with I don't know tens of thousands of elements then it would make sense to make this more efficient and there are hooks to make this more efficient we could execute the sort function only when the todoist props changes and not when any other state changes but this is an optimization and you should only do this if this operation here is actually expensive and in our case with a relatively small array this is a very cheap operation and we can easily execute this with every render if you want to see examples of these more advanced cases check out my bigger project tutorials where we implement the stuff okay next I want to add a way to delete todos I hope by now you left your comment with your delete logic don't be scared of this then we go into our to-do item component and this is why we have this outer div here inside this div but outside of the label I want to put put our delete button so lowercase button in here we want to put this trash two icon which is an import from lit react the package we installed earlier we set the size which is a prop by the way to Trend here we close this there is the icon we want to style this a little bit I want to give this text Gray 500 to make it gray then we want to St the diff to align these elements properly we make this a flex box to have them in one line item Center to Center them properly and a gap of one for some spacing to the label here we add another class we can put it at the start or end doesn't really matter grow which again makes this take up the full aailable width minus the icon then we go down to our button again to the button we also add a Class A padding of two and lastly on this button we need an onclick Handler to which we pass an aror function without arguments again we don't put this into a separate function because it's only a single line here we want to call our undelete callback which we haven't created yet so let's do that now here on the to-do item prop we declare the same on delete callback that we have in our to-do list this one here put it here D structure it down here then call it into onclick Handler and to it we simply pass the idea of this to-do that we render here okay we render our to-do items in our to-do list right this means now this expects this on delete prop and we want to forward this to the parent page so again we pass this call back here and then the last step is in our ftsx file where we now have to pass this delete callback for which again we want to create a function delete to-do for organization so here above the return statement we put function delete too which takes the ID of the deleted to-do as an argument again we have to update our state with set to-do again we get past the pref Todo and we have to return a new arrayer where the item we deleted is removed and in react you do this with the filter function so we take pref Tod Doos we call filter here we get pass an error function with each to-do and then we want to keep every to-do in our list except for the one that we deleted so here we check if too. IDE is not equal to the ID we pass to this function only then we want to keep it in the array and the one ID that matches we want to remove from this array and this is how we update our state to delete an item let's try it out we can click this button and the item is deleted when we refresh the page they all back we can also add new items and delete them we can check them delete them nice two more things for one when we add a lot of items at the bottom there is no padding anymore we can fix this by going to the main tag here and adding overflow y Auto now we have the proper padding here at the top bottom which is just a detail secondly I also want to add an empty state so when we remove all to-dos I want to have a little text that says you don't have any to-dos in your list yet and this is also an interesting topic because we will learn how to render a text conditionally so let's go into our to-do list component again and we want to render this empty text outside of this div here but a return statement needs one parent element so we can't put another diff here below because then we have two parent elements so we could either wrap this into another diff but then we have an unnecessary diff that we don't really need another thing we can do is we can use an empty fragment like this this allows us to basically put multiple parent elements in here which will then just be rendered inside the page so inside this fragment below this div we add an expression where we write to do. length we want to check if this is equal to zero so if this array is empty then with two Embers and signs so the logical or operator in JavaScript we can render a component conditionally only if this expression here is true so here we make a pair of parentheses and we simply want to render a paragraph that says no Todo yet add a new one above or whatever you want us to say and I also want to style this paragraph a little bit there already is but I want to Center the text with text Center I want to make it smaller with text SM and I want to set it to gray 500 nice and this element is rendered conditionally so when I added to-do it's gone when I delete this to-do it's there again and again this is really the beauty of react your whole UI is in zinc perfectly you don't have to worry when to show or hide a certain text you just declare under which conditions you want to show it and then react takes care of always drawing the latest State on the screen okay we still have some lint errors here we just have to remove this import statement and then it's all fine next I want to create a new component that shows how many to-dos we have completed and afterwards we get to a new important topic and that is how to execute side effects in react so make sure you don't miss that so let's create a new component in our components folder we know the drill by now and we call it to do a summary. TSX export default function to do a summary it will take some props interface to do a summary props we are Pros with this by now this needs the to-do array so to do array and we also want to add a callback delete all completed because this section of the UI will have a button where we can delete all completed todos at once and of course we have to pass this as a callback because the state lives in our page then as usual we have to destructure these props in the component arguments to do a summary props and here are the todos and the carback in this UI element I want to render the number of completed to-dos so let's create a const completed Todo and we assign this to to-dos do filter where we take each to-do in this error function and we only want to keep the completed ones in this list again this filter operation will be exec it every time this component is rendered and again this is fine because this is a cheap operation we can do this directly in the component body and then we render a UI element we put a diff in here which we Style with text Center and space Y2 in this diff we put a paragraph tag which we render completed to do do. length then outside of the curly braces is slash another pair of curly braces to do. length the unfiled array and then outside it will say as text to do completed let's save this for now P this into our app I want to put it outside of this div that contains the form and the to-do list so below the diff above the main closing tag we put the to-do a summary component which requires that we pass the Todo list to it and this delete all completed callback for now we just pass an empty error function like this so that the code compiles but we handle this function later and there is our text now let's refresh the page and check one of these components and as you can see the State updates immediately I want to style this text a little bit so we add class names to the paragraph text smm and font medium and then what I want to do is if this number is above zero I want to show a button that triggers our delete all completed callback we already know how to do conditional rendering right so below the paragraph we add a pair of curly braces we check that completed to-do do length is greater than zero use two erson signs to render a component conditionally or a normal HTML element parentheses in here we put a button which will say delete all completed the onclick Handler of this button will call our delete all completed callback and then we style this button RI text red 500 hover colon underline text smm and font medium so those are all the classes and this is the result this button is only shown when we have at least one checked to do so let's format this properly save this and then handle this callback here in our app page so we need a new function called delete all completed to-dos we don't need any arguments here again we need to update our to-do State again we need the breath to-do and again I recommend that you pause the video for a moment and try to figure this out yourself we already have the normal delete to-do function right how would we write this to filter all completed todos it's not that difficult okay so three to one solution we call breef Todo we call do filter again but this time we filter all todders that are not completed so we put an exclamation mark here in the beginning we only want to keep the to-dos that are not completed in this new array and set our new state from this updated array and now we simply have to pass this function down here by its name and that's it and then we can check Todo we can delete them all at once we can add new to-do this can delete them as well and there is a bug in our UI which of course I put there totally on purpose I swear but it's a pretty simple bug um here for the ID of the new to-do we pass the length of the current array plus one the problem is this way we use values that we already used before because if we add a fourth element and remove the third one and then add another fourth element then two elements will have the ID four and our list will not work properly anymore as we just saw because this deleted the wrong to-do when I click the delete button so again in a real production app this IDE is coming from your database so you usually don't have to worry about this but here we need a unique value and the simple way to handle this is to just use the current timestamp in milliseconds with date. now the shots of files now every idea should be unique and our list should work properly so let's see we delete a few items we check some we delete some more check uncheck check add new items delete one of them and and it all seems to work right okay next we will learn about side effects and then we will create our own custom hook to better organize our code and then we are done with this beginner tutorial but you don't want to miss these two topics okay we already know that we can use callbacks to execute some code when we click a button or submit a form or have some other user event but sometimes you want to execute a side effect when a state changes or when you render the component on the screen for the first time now again we can't put this logic directly into the component body because then it will be executed with every single render instead we execute these side effects in a use effect which is another important react to let's put it above our functions here but below our use State we call this use effect hook to which we pass an error function which gets a block of curly braces and and then we have to pass a second argument to this function which is an array this array contains the dependencies when we don't pass anything inside this array this effect will be executed when we first put this component on the screen not with every single render only the first render when we put a state in here like the to-do state for example or we can also put a prop in here then this effect will only be executed whenever this value changes for this example I want to store our to-do state in the local storage of the browser to save the current state across refreshes but doing this with every single render would be very unnecessary right but we also don't want to have to click a save button instead we want to save this whenever the state of this to-do's array changes so whenever we add or delete or update an item we automatically save it to local storage so and in here we just have one line loc storage. Z Item we have to give it a key in form of a string let's call it Todo and in local storage we can only save strings so we write Json in all uppercase do string fi and pass our to-do array and this turns this into a string and saves it a local storage every time the to-do State changes and we can already see this in the Chrome Dev tools with F12 we can go to the application tab here we can view the local storage there's already the todos array you can see it down here and now whenever we change something our use effect stores the updated value in local storage and it's always up to dat but when we refresh the page P we also want to load this state from local storage right we could do this in another use effect with an empty dependency array which again gets executed only when the component is rendered on the screen for the first time but a simpler and more efficient way is to do this directly in the use State initializer instead of our dummy data we can also pass an error function here like this execute some logic and then return the initial value in here we want to get our saved todos from local storage since we turn them into a string we have to turn them back into an object which we can do with jon. pass and in here we pass local storage. get item with the same to-do is key make sure these Keys here are identical but get item can return null if this key doesn't exist in in this case we want to fall back to an empty array but this has to be a string because we are still inside this json. pass function okay so we have our save Todo and now we want to return this but we want to check if saved too. length we don't get autocomplete here because it doesn't know what type this is we can set the type explicitly as a to-do array so if save to-do do length is greater than zero question mark we want to return save todos otherwise I want to return the dummy data so if we delete all our items and we refresh the page I want to put the dummy data into local storage and into our array so this is what we put in here let's refresh the page just to be sure so now we can add new items we can check off existing items and when we refresh the page we get the previous state nice now this is stored in local storage when we delete all todos and refresh the page we get the dummy data again which again is saved in local storage so now you already know 70% of the stuff that you need in react one more thing I want to do in this tutorial this logic here is really messy it's a lot of code in this one component right we can organize this better by putting it into a custom hook so let's do that next so as I mentioned before all these functions here that start with the word use are called hooks in react use State use effect and there are some more these hooks can only be called inside components or inside other Hooks and how can we create our own hook well we simply create a function that also starts with the word use so let's do this let's create a new file in the srz folder first we create a folder called hook Hooks and in here we put a hook called use too. TS not TSX just TS here we export a default function called use todos this time with a lowercase U because this is not a component and then we go back to the app. TSX and we take all of this code we start here added to do state with the use effect and all our fun functions everything above the return block we cut this out we paste it here directly inside our use to lose function we have to fix some imports so let's import all of the stuff I just removed the last letter to use Auto Import we need our dummy data use effect and that should be it the other ones are just aus functions so why do we have to call this used too now when we try to change the name for example to get Tod do we actually get a warning here which says react H use state is called in function get toos that is neither a react function component nor a custom react hook function react component names must start with an uppercase letter react hook names must start with the word use and that's the whole point here whenever you want to extract react hooks into a separate function this function has to start with the word use that's a naming convention and this naming convention is enforced because otherwise react developers wouldn't know that inside this function we use react Hooks and this would make it really hard to write and debug react code because if State and side effects are hidden in normal looking functions then it makes it really hard to understand what is going on this is why we have this naming convention and this is how you create a custom hook in react it's not magic the hook can also take arguments if it needs some ours doesn't but we still need a way for our app page to use these functions and values in here right and we can do this by simply returning them so all the way at the end of this function we add a return statement and here we return the to-do State our different functions set to do completed add too delete all completed and delete too there should be all of them then we go back into our page we create a cons that we destructure and we call our new used Todo hook and in here we find all these values our state add too set too completed delete to do and the deal are completed we remove the unused import statements and now our app works the same way as before just that our code is much more organized because all this logic is hidden in this hook and again we can reuse this in different components if we want to let's try if it still works refresh the page is still stored in local storage we can add to do is delete completed and it all still works exactly the same perfect I hope you enjoyed this react beginner course again I highly recommend that you also get my free react best practices email course it's the perfect compliment for this tutorial I will teach you a small react best practices every day for a few days again you can find it under coding andf flow.com react bestest practices but of course this is just the beginning there are more topics you have to learn like how to use databases routing fetching data metadata serverside rendering and some more advanced react hooks I always recommend that you learn these Advanced Topics by just building projects because this is the most fun and I have a full web def playlist here with a ton of different projects most of them are in nextjs I also have a m course where we build a separate expressjs back end whatever you prefer just check out my web def playlist if you want to learn nextjs in particular I have a nextjs 14 beginner tutorial but it's inside this playlist as well so I will link the playlist and all the other resources you need don't forget to subscribe to the channel for more tutorials in the future and also please leave a like on this video because it really helps this video and this channel grow and if you know someone who would like this tutorial or any other of my tutorials please share them because this really helps me which in turn motivates me to make more videos all right and then I see you in the next video Happy coding take care
Info
Channel: Coding in Flow
Views: 13,955
Rating: undefined out of 5
Keywords: react beginner, react beginner tutorial, react beginner projects, react beginner course, react beginner mistakes, react beginner tips, react beginner tutorial 2024, react.js beginner, react.js beginner tutorial, reactjs projects for beginners, react.js beginner projects, react js beginners, react js beginner guide, react basics, react basics tutorial, react basics crash course, react basics project, vite react, react, react tailwind css, react TypeScript beginner, react js
Id: siTUv1L9ymM
Channel Id: undefined
Length: 104min 19sec (6259 seconds)
Published: Sun Feb 11 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.