All React Hooks Explained in 2 Hours | Complete React Hooks Tutorial with Example 2024

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome back to another exciting tutorial of great stack in this video we are going to learn everything about react hooks we will learn what is react hooks then we will learn all important and most commonly used react hooks with example and we will also create our own custom hooks so let's understand what is hooks hooks are a special functions that allow us to use a state and other react features in functional components earlier we used to create react app using functional component then we did not have access to the state management and life cycle methods to access these features we had to add the class components so this was the problem with functional component but after introducing react hooks from the version 16.8 we can now use the Estate Management and other react features without writing class components in other words hooks are the functions that makes functional component work like class component hooks made react functional component so easy to use that's why most developers prefer functional component over class component so what is the benefits of react hooks react hooks simplify the code improves the readability reusability and overall performance of the application there are multiple hooks in react and some of the most commonly used hooks are use a state use effect use ref use memo use callback use context use reducer use layout effect and we can also create our own custom hooks in react so in this tutorial we will learn all these hooks one by one with practical example so first let's learn user State hook in react user state is a react hook which create an a state variable which help us to track a state in components and update the user interface when a state changes first let's understand why we need user state so let me take one simple example to update one text on web page here I have created the basic react project and we are in the app.jsx file and this is our web page which is clear right now so just come back and here let's add one simple program to display some text on the web page and we will add the button and using that button we will try to change the text so here let's add the text in H1 my favorite color is red then we will add one button and here we will add the text blue if I open the web page here we have this text and here we have the button now we have to remove this color from here and we will store it in one variable so here let's add one variable we will add let color equal to red and we can add like this this color variable so after that we will open the web page so you can see my favorite color is red and when we change this one we will make it blue so you can see head is displaying color blue but I will keep it red and when we'll click on this button it should display blue for that we will create one function so on this button we will add the on click and here we will pass one function so we'll add the function change color and add this function here just add const change color and one add a function so here let's add same variable which is color We'll add color here and in this one we'll add blue so now when we'll click on this button it will execute this function change color and it will assign the value blue instead of red so let's test it on the web page and here it is displaying my favorite color is red and when we click on this button it is not changing but we have added this color is equal to Blue so why it is not working let me add console log and here we will display the updated value of this variable which is color and open the web page let's open the console tab now if I click on this button blue you can see the text in this console it is displaying blue right but why it is not displaying the text here so the value is getting updated and it is getting printed in this console but it is not updating the UI for that we have to use use State hook so let me solve this problem with use state to use the use State hook first we have to import it from the react Library so here let's add import CES and we'll add user state so we have imported us state from react so let's store this one in any variable so here let's add const here we will add any name so let me add one name counter equal to and we will add user State and in this user State we have to provide the initial value that we want to store so if I write like this so zero will be the initial value now let's print it we will add console log and here we will put counter and remove this console log previous one save the changes and in this console you can see here we have one array let me expand this array so in this array you can see here we have the initial value that we have added that is zero and the second one is one function so we can store this value and this function separately right and these values are in one array so we can access the first value with index zero and second value with index one so let's add this here we will add us the state then index zero so it will give the first value we will store it here in counter and second one was the function so let's duplicate it here we'll add any other name so let me add set counter and here we will add index one right so we will get both values separately and let's print it we will print counter and and set counter now just come back so you can see in this console so we can store these values in one aray so let's come back so instead of this counter we will add one aray and in this aray here we will add one variable name so name is counter then we will add one function name so let's add the function name set counter so in this counter we will get the initial value if we have added zero 0 will be stored in this counter and this set counter is used to update the value of this counter variable so if I add 10 and let's see the console you can see it is printing 10 let's come back so this is the syntax to declare the state variable using use State hook now we will use this syntax to declare the color state so let's remove this one and uh here let's add const we will add color and the setter function set color like this and we will use user State and here we have to provide the initial value in this one we can provide any data type like a string Boolean number anything so here we will add string red so the initial value will be red save this changes now you can see here we are updating the color so for updating this color we will use this Setter function set color so just copy this one remove it here just add set color and in this one if we pass blue it will change the state variable value and it will also update the UI so after adding this save the changes and let's see the we page right now you can see the message my favorite color is red and when I click on this button blue you can see the text becomes blue so it is working right let's refresh the web page and try it again here it is is displaying red and when we click on this button it becomes blue so you can see in this use a state variable we have added the initial value red that is displaying in this H1 then we are changing the color using this button when we click on this button it calls this function change color and we are updating the color using the setter function which is set color so so this is the simple example of user State variable now let's see another example where we will create multiple State variable so let me clear everything let's clear this one also here we have imported user state it will be there now here let's add one text in H1 my brand and after that we'll add one text in B tag it is a red roma from 2023 and Here Also let's add Ferrari save the changes and let's open the web page here we have the text my ferari it is a red roma from 2023 this text is very small let me add it in S2 now it is looking good next we'll store these values in variable so here let's add a state variable so we'll use the syntax const brand and the seter function name will be set brand equal to user State and here in this user State we will add the initial value let's duplicate it and we'll create multiple State variable this will be model set model this will be here this is set ear and this will be color let's add set color and initialize the variables with different value we will add Roma here we will add 2023 here we will add red instead of this text we will add cly presses and we will add Bland here we will add color then we will add model and here we will add ear now if I open the web page so now you can see it is also displaying the same thing my Ferrari it is a red roma from 2023 but in this case we have declared multiple State variables right so instead of creating multiple State variables we can create a state object right so let's remove everything here just add car and we will add the function Set Card like this and uh here we will remove this remove other create variable and we will initialize it with one object so we will add curly presses for object in this object we can store the data in key value pair so in this one let's add Bland and we will add ferar then we will add model then here then color and here we have to add like this we have to find the brand name from this card object so here just add card. brand like this we have to find the model from this card right so just add car car do model we will add car do color and car here so here also we will get the same result you can see it is same now I want to update the color in this text instead of this red we will add blue so how to update the data in this object that we have created using this user state right so for that we'll create one button let's add button and button text will be blue and here we'll add one function so we'll add the on click event it will be update color or change color so just copy this and here we will add this const change color and it will be addo function using this function we have to update the color in this object so for changing the values in a state variable we have to use the setter function so the setter function is Set Card let me copy this one paste it here we'll add set card and in this set car we have to update the color only right so if I add like this color red what will happen it will replace this complete object with new object in the previous object we have four data model brand ear and color and in this one we are adding color red if I save the changes open the web page and when we click on this button you can see it is displaying my it is a red from and the other things is invisible because in this object we don't have the brand name we don't have the model we don't have the color so this is not the right way to update the object using the setter function so to update the object we will use the previous value so let's add one Aro function here like this in this seter function we have added one Arrow function right and in this parameter we will get the previous value we can write any name here so simply I'll write previous like this and in this one we have to return the previous value so we will use the spread operator and we will add the new data that is color so just comma and color blue now what will happen it will spread the previous data and it will update the color so after adding this let's open the web page refresh it now here we have the message it is a red roma from 2023 if I click on this blue you can see the message it is a blue Roma from 2023 so it is updating the user interface and it is updating this object also that we have created in the user State variable in sheet of this PR we can write any name suppose we add car and here also car it will work you can see when I click on this button it is working it is displaying blue so in this parameter we will get the previous value and we can spread that previous data then add the new value that you want to update so this was another example of user State hook where we have stored the object in use State variable now let's see one more example of updating a state based on previous state so let me clear everything and let's clear this text here we will add title count and let's add zero and here we will add on click and in this button text we will add increase and here we will add the function that will increase the count so just add increase count next here we will add the state variable so just add const it will be count then set function name set count equal to user State and initial value will be zero and instead of this we'll add count so this will be count zero on the web page now we have to declare this increase count function so just add const increase count equal to one Arrow function so here you can see count zero and here we have the button increase now in this one let's add set count and in this one we'll add count + 1 what will happen it will increase the counter value by one right so just come back and here if I click on this button you can see the counter is increasing by one if I click again it is increasing by one right when we click it increase the current value by one so it is working fine now what will happen if I duplicate this one four times and here let me add increase by four so I want to increase the counter by four if it is zero it will directly come to four then it will come to 8 right Let's test it refresh this one so the count is zero when we click on this button you can see still it is increasing by one like this so why it is happening because it is in the running State and it is not updating the UI when we will add this set count for the first time it will get the value from here initial value and it will be 0 + 1 = 1 again here also it will take the initial value that is stored here and it will be 0 + 1 1 here also it will give one and this is also one so that's why the counter is increasing by one when we click on this button now how to update this counter by four for that we have to use the previous estate value so let me remove this comment and uh instead of increasing the count directly let's add one Arrow function like this and in this Arrow function we will get the previous data like this and here we will add previous + 1 when we have only one parameter we can remove this parenthesis and when we are adding one line of code so we can remove this one also so it will be simple now if I duplicate it and click on this button it is increasing the count by four it is four when we click again it becomes eight when we click again it becomes 12 so it is working we can write anything here instead of this P we can write like this count you can see it is also working 32 then 36 40 right so what is happening here first it will take the previous value that is 0 so 0 + 1 will be 1 then the previous value will become 1 and here it will do 1 + 1 is equal to 2 after that here we will get 2 + 1 is equal to 3 and here it will add 3 and 1 that will be four so when we click on the increase by four button it will increase the counter by four so this is how you can use the previous value of the state so using the state variable we can update the user interface so this was all about the user State hook in react now we will learn use effect hook the use effect hook allow you to perform side effects in your components some example of side effects are fetching data from API directly updating the Dom element and timers like set timeout and set interval so let's see the Syntax for the use effect to use the use effect we have to import it from the react Library so we can import like this cly bres use effect from react we can also import this in same line let's move it here put a dot here just add one dot remove this line so in the first line we are importing react and use effect from react library or there is one more option let me remove it and here if I type within this function component we will add use effect and select it from this snipet you can see automatically it will import this one from react Library so let's see the syntax to use the use effect we have to provide two things first one is the Callback function and the next one is dependency so let's add D so this call function is required but this dependency is optional we can remove it like this it will also work we can just add the call back function in this use effect but if we add the dependencies so we have to add it in the array like this we can use the empty array also and we can add some variables in this array so there are three ways to use use effect the first one is without any dependencies and the second one is using empty aray and the third one is using aray with variables like we can add number of variables here with a comma within this square bracket so let me remove it and now let's understand it with one example so here we will display one counter that will display how many times component gets loaded so in this return let's add one text and here we will add the text I have rendered zero times we will not put zero here we will add the value using the state variable so here we will use the state variable with the name count so just add const we will add the name that is Count then we will add the setter function set count and here we will add user state for user State also we can select it from this snippit and it will automatically import this user state from react Library so in this one we have to provide the initial value for user State let's set it zero so the count will be zero and we will display this count in this message like this so after adding this if I open the web page you can see the message I have rendered zero times now I will add one timer function that will update this counter value y one after 2 seconds so for that let's come back here we will add the use effect just add use effect and we will use the first option we will use the use effect without any dependencies so here in this use effect we have to provide one call back function so let's add one Aro function and in this function we will add the timer function like set timeout so just add set timeout and uh in this set time out there will be one function and this function will get executed after 2 seconds so let's add 2,000 milliseconds so this timer function will increase the counter value y1 so to change the counter value we have to use the setter function that is set count so let's copy this one set count and here we will provide the previous value so just add count then Arrow function it will be count + 1 so it will increase the counter by one after 2 seconds now if I save the changes and let's open the web page you can see it is increasing the counter but here we have one problem Let me refresh it you can see it is directly going from 0 to 2 it should go 0 1 2 like that but it is going like 0 and two to fix this one let's come back and uh we will open main. jsx file so this problem is happening because of this react strict mode react strict mode is additional runtime checks in the development envirment to make sure your app is safe so to turn it off we have to remove this one just remove this that's it now if I open the web page you can see this counter will start from zero and it will go one then two then three so at every 2 seconds it is increasing the value by 1 now here we have another problem like you can see we have added set time out so the set time out execute the function only one time so it will increase the value by one that's it but why it is increasing continuously it is increasing the value continuously after every 2 seconds so why it is happening it is because we are using this use effect without any dependencies so when we use the use effect function without any dependencies then it will execute this call function whenever any state State change in this component so you can see here we have the counter state right so this counter state is changing at every two seconds and when the counter state is changing it will again execute this call back function that's it let's understand it again here we are using use effect without any dependencies so whenever we are using use effect without any dependencies then it will execute this function whenever any a state change in this component so in this component this count is changing at every 2 seconds so at every 2 seconds it will again call this function and when this function will be executed it will increase the value y one at every 2 seconds that's why it is continuously increasing the value by one for this counter now let's see this second example if we add one dependencies so we will add the empty array so here we have the use effect right so here let's add comma and we will put empty are so in this use effect we have added one function this is the Callback function and here we have added one empty aray so whenever we are using the empty aray then it will execute this callback function only once when the comp component gets loaded right so let me save the changes open the web page you can see it will increase the counter value y one and that's it it is not continuously increasing it it increase the counter value by one only one time right why because here we are using empty aray in the dependency so when we are using the empty array it will execute this callback function only one once so it will execute the set time out only once and it will increase the value from 0 to 1 that's it now let's see the third option in the third option I told you we can use any variable in this array so let me put this count here within this array so what will happen when we put this count here so it will execute this function when the component gets loaded and after that whenever this count changes it will again execute this one so as you know here we are updating this count by one so after 2 seconds it will change this count value so it will again run this one let me show you this on the web page so you can see it is increasing the counter value y 1 at every 2 seconds so y why it is happening this time because in the dependencies I have added count it means whenever count changes it will again execute this call back function and it will also execute this call back function when the component gets loaded first time and whenever the count changes it will again execute this function and here we can add multiple values multiple variables suppose in the application we have other variables like name set name and greatest tack right so we can put this one also so whenever this name will get changed then this function will get executed so we can add multiple variables multiple state in this array so this was all about the use effect hook in react now we will learn about use ref hook so what is use ref us ref is a react hook that allow us to create mutable variables which will not rerender the component it means when we create the variable using us ref and when the variable value changes it will not rerender the component USF is also used for for accessing Dom elements it means we can access the Dom elements using the US ref hook and we can modify the Dom elements now let's understand it with an example why we need use ref hook we will create one counter that will display how many times our component gets rendered so we will create this example with the use a state so let's add one use a state variable we will add const then variable name that is value and Setter function is set value it will be user State user state has been imported and we will add the initial value zero now let me duplicate it and and uh here we will add count that will display the number of count so let's add the setter function set count and initial value is zero now we will display this on the web page so here let's add one button and the button text is minus1 that will decrease the counter value by one and we will add one more button it will be + one that will increase the value by one and within this we will add the value so just add the H1 tag and we will place this value like this after adding this let me open the web page so here we have minus one and + one we have two buttons and here we have the value which is zero now let's come back and when we'll click on this button it should decrease the value by one when we will click on this button it should increase the value by one so here let's add the on click event in this one we will add one Aro function and in this Arrow function let's use this set value that will update the value so in the set value we will take the previous value and in this previous value we will increase the value by one so just add previous minus one let me just copy this one and paste it in this button which is the second button and here instead of M minus we will add plus so using this seter function we are updating this value now if I open the web page and click on this plus you can see the value is increasing let's click again it becomes two so this value is increasing and when we click on this button the value is decreasing now below this one we will display count that will display how many times the component gets rendered so just come back and uh after this button let's add H1 tag and we will add render count just insert this count that we have created using user state so till now we are not using the US ref we are using user state so let's see what happens here we have have render count zero right next we have to increase this count whenever the component gets rendered so here let's add use effect click from this snippet so it will import this use effect from react library now in this one we will add one add function and use this set count here we will take the prvious value and uh increase the previous value by one so previous + one in this use effect I'm not using any dependencies so what will happen so when we use this use effect without dependency then this function will be executed whenever any state changes so save this changes and let's open the web page so you can see this counter is increasing continuously so here we are facing one issue this counter is increasing continuously so it will run this counter in infinite Loop this problem is happening because user State itself causes rendered let me explain it again here we are using user state for this counter or count so whenever the component gets rendered this count value is getting increased by one so whenever this count value gets increased by one again it will rerender the component because whenever this count gets updated it will change the state and it will reender the component that's why it is running this count till infinite so to solve this one we will use use ref hook because the used ref does not rerender the component when it is changed so let's come back we will replace this one let's remove it and instead of this we will add the counter using us ref so let's see the US ref first so let me remove this one also remove this count also now this web page is working let's come back and here first we have to import the usev so we can add like this us ref from react liity now let's add const count is equal to USF and in this user ref we have to add the initial value and this is optional let me add zero after adding this let me just print this count in console just add console.log count like this so we have used this use ref hook and stored it in count now we will print this count in console Let's see we will open the web page open the console here you can see we have one object right now in this object you can see we have current property let me expand it you can see we have current and zero this zero is the value that we have stored here if I change it let's say 10 now you can see this current and value is 10 so we can access the value using the current property from this object so let's come back and uh remove this console log and we can use this count here now to access the value from this count we have to add dot current like this now this number which is 10 will be displayed in the render count it is displaying 10 now let me remove this fixed value I will add zero now we have added the count value zero now it will increase the counter whenever the component gets rendered so just add use Effect one Arrow function in this one we have to increase the counter value so just add count dot current for updating also we have to use count. current right and let's add equal to count. current + one like this and here also we are not using any dependencies just save the changes and open the web page now the render count is zero when I click on this plus button render count is one again click on this button render count is two let me click here render count is three let's click on minus again render count is four so now this counter is working properly because this use ref is not rendering the component whenever this count is changing but instead of this used ref if we add use a state then this count value will be changed and when the count value will be changed it will rerender the component that's why we use us ref Hook when we don't want to rerender the component when the value is changed now we will learn about the another use of use ref hook that is is accessing the Dom element so let me clear this example and let me clear this also and here let's add one input field after that we'll add one button and in this button We'll add click here let me open the web page you can see we have one input field and one button click here now let's come back here we will add const and we'll select this input element so let's add input element or you can write any name and in this one just add use ref like this us ref is already imported here so we can write us ref next we have to connect this use ref with this input field using the ref attribute so just add RF ref and provide this one input element that's it so this is how we can simply access the Dom element using the use ref now let me add the click functionality on this button so that you can see what we will get using this input element so just add on click here we will add BN clicked and Define this one const BTN clicked one Aro function and uh here just display this input element in console so we will add console log input element so what is happening here this us ref is selecting this input field when we click on this button it will display the input element in the console now let me open the web page open the console tab now we will click on this button click here you can see here we are getting current and input like this you can see we have current and input so to access the element we have to use the current property so just come back and uh with this input element we will add do current like this input element do current and now if I open the web page refresh it click on this button you can see we are getting the HTML element which is input field so this is how we can use the US ref for selecting the Dom element now let me add something else when we click on this button so let's come back and uh after this console log let's add input element do current that will select the input field on this input do current we will add the style dot background equal to let's add the blue color save the changes now if I click on this button you can see it is displaying this element in the console and it is also changing the background color of this element so so like this you can use this use ref hook to select the Dom element and modify the Dom element so this was all about the US ref hook in react now we will learn about use memo hook the react use memo hook returns a memorized value it is like catching a value so that it does not need to be recalculated the use memo hooks only runs when one of its dependencies gets updated this can improve the performance of the application there is one one more hook in react to improve the performance that is use callback hook the use memo hook and use callback hook are similar the main difference is use memo hook returns a memorized value and use callback hook returns a memorized function we will learn more about use callback later in this video so why we need use memo let's understand it with an example so let's create two State variables const the variable name is number and the seter function name is set number is equal to user State user state has been imported and initialize this number with zero now we will add one more State variable that is counter Setter function name is set counter and here also the initial value is zero now we will create a function that will calculate the cube of any number so let's add one function Cube num and here we will add the parameter num and uh let's add console.log and in this one we will add a message calculation done and after that we will add the return statement and it will return the cube of this number so for that we will use math. power and provide this number then provide Power three so it will return cube of this number now we can store the result in any variable so let's add const result is equal to Cub num and here we have to pass one number and we will get the number from this state variable let's pass it here like this in this return statement we will add one input field where we can enter any number and below that we will display the cube of that number so just add one input field input type will be number and below this input field we will add one title in H1 and here let's display cube of the number and here we will display this result after that save the changes open the web page so here you can see we have one input field and here we have one message cube of the number is zero right now if I enter something in this input field nothing is happening but I want to add the number here in this input field and here instead of this zero we have to display the cube so just come back here in this input field we will add the onchange property add onchange let's add the AR function we will get the event and now we will update this number using this Setter function which is set number so let's add set number and here just add e do target. value like this and in this input field we will also add value and in this value we will add this number State variable that's it so after adding this save the changes and open the web page you can see if I type 10 here we are getting 1,000 so it is displaying the cube of this number if I type five here we are getting 125 so this Cube calculation is working fine now let's add one more button here after this H1 we will add one button and the button text is counter Plus+ that will increase the counter so you can see here we have this counter right so we have to increase this counter so on this button we will add the on click event and here we will add one Arrow function and in this one we will use set counter we have to increase the counter value y one so just add counter + 1 like this and below that we will display the counter value so just add H1 and let's add counter and uh we will add curly Braes and write this variable name counter save the changes open the web page you can see here it is displaying counter zero if I click on this button counter Plus+ it is increasing the value if I click again it becomes two let's click again it becomes three so this counter is also working and this number calculation is also working now if I open the console tab refresh this web page so here you can see calculation done so this calculation done message is coming from the cube function now if I click on this counter the counter is increasing but it is also executing this calculation function that's why we are getting this message calculation done this calculation done message that you can see here is coming from here that is written in this CU function you can see we have added calculation done so here we we are not updating the number in this input field but still it is calculating this Cube because when we update this counter it changes the state and it render the web page and when the web page is rendered it is recalculating this Cube using this function so to prevent this function to recalculate the cube we can use use memo hook so now let's solve this problem with use memo hook so first we will import use memo just add use Memo from react library after that here we are simply calling this Cube number function so let me remove it and here we will add use memo this Ed memo accept two parameters one is call back function and second one is dependencies so here we have to add one function just add one Arrow function and uh here let's add return and we will return the result of this function that is Cube number function and after that we'll add comma and here we will add this a square bracket and in this one we have to provide the dependenc see so let's provide this number copy this one paste it here here we are returning this in one line so we can remove this curly bres and uh return a statement we can simply write like this also it will work now what will happen here when component gets rendered it will not execute this function it will only execute this Cube number function when this number gets changed so let's see this on the web page right now it is displaying cube of number zero and counter zero if I click on this button counter Plus+ the counter is increasing right but it is not rendering this function it is a still zero here we are not getting any message of calculation done right but if I add some number in this input field let's add three you can see it is giving the result 27 and we have the message calculation done okay so whenever we type anything in this input field so this input field will update the number let's type six so here we are getting the cube of this number six and here we are getting calculation done second time right so this calcul ction function which is the number calculation is getting executed whenever we add any changes in the number and when we add any changes in this counter this counter is rendering the component but it is not executing this function so this will improve the performance of our application so this was all about the use memo hook in react now we will learn about about use callback hook use callback is a hook that lets you catch a function definition between renders it means when we use use callback hook it do not create multiple instance of the function when render happens instead of creating new instance of the function it provides the cached function on render of the component so why we need use callback hook let's understand it by taking an example so first we will create one counter so let me create it quickly here I have added one use State variable now in this return we'll return the count in H1 and after that we'll add a button that will in increase the counter value and button text is click here and here we will add the on click event that will increase the value let's add one Aro function and to update the counter we have to use this seter function which is set count so just add this set count we will add the previous value and we will update this previous value by adding one that's it and here we are using user state so we have to import it so in this import statement we will add comma curly bres user state from react library now save the changes and open the web page here you can see we have the counter value zero and we have the button that will increase the counter you can see it is increasing the value now we will create a new component and the component name will be headed so let me come back to the vs code and in this SRC folder we'll create a new folder with the name components and in this components folder we will create a new file and write the file name header. jsx so we have created a new component header we will add R fce now in this component we will add a message in S2 header and here we will add one message in console also so just add console log and the message is header rendered now we have to mount this component in this app component so here before this H1 let's add header we will select it from here so it will import this header from components slhe header close this tag so in this app.jsx file we have mounted this header component after that we have this counter then we have this button now if I open the web page you can see here we have the header that is coming from the header component then we have the counter and this button now let me open the console so in this console you can see this message header rendered because we have added this message in the header component here right now let's come back to the web page again and now when we click on this button click here let's see what happens when I clicked again you can see the message header rendered let's click again you can see another message header rendered two times click again it is for three times so you can see I'm updating this counter we are not updating anything in the header component but still header is getting rendered multiple times because when we are updating the counter it is rendering this app component and in this app component we have mounted this header that's why it is rendering the header component also to fix this isue we will use the memo method that comes under the react package so let's open header. jsx file here we have imported react so from this react we can use the memo method so in this export a statement export default let's add react dot memo and wrap this header that's it save the changes now let's open the website again let's refresh it so you can see header rendered for one time now if I click on this button that will increase the counter the counter is increasing but it is not rendering the header you can see the header rendered only one time so this problem got fixed right next we will create new function let's come back to the code again open app.jsx file and here let's add new function const and function name is new function and it is just one Aro function like this we have just created one function next we have to pass this function as a props in this header so here we will add new function equal to curly bres and new function so what we are adding here we have created one function using this Arrow function and then we are passing this function as a props in this header that's it after that we will save the changes and test our website again you can see it is displaying header rendered again let's click on this button again it is displaying header rendered let's click again on this button again it is displaying header renders we have two times so you can see when we are updating the counter it is again rendering the header component which is not required because we are not changing anything in the header we are just passing the function and this is the same function so why this is happening it is happening because of the differential equality let me explain you the referential equality with one example so so let's come here in this console we'll clear it and here let's declare a function const fub1 equal to one Aro function and in this function we will just add hello so we have created one function F1 now let's add one more function and the function name is F2 it is also one Arrow function and here also we will add hello now we have two functions fub1 and FS2 fub1 is returning one message hello and FS2 is also returning the message hello right now let's compare this function using the equality check so just add fub1 triple equals F2 so you can see the output it is displaying false right so why it is displaying false so here we have created two function fub1 and FS2 and both function have been created on different memory location so it is not the same function these are different that's why it is giving false so in the same way when we read under this component it creates a new instance of this function right and when we are mounting this header component and providing this new function as a prop so every time we are passing a new function so when the props is changing that's why this header component is rendering again let me explain again when we rerender this app component why this app component is getting rendered because we clicked on this button that will update this count and when this state is changing it will rerender this app component correct now when this app component is rendering it will again create a new instance of this function here in this one we are mounting this header component and in this header component on every render we are passing new function that will be different every time we are passing new function it means the props is changing so whenever the props are changing then this header component will render again now we can solve this using the use callback hook so let's see how to implement the used callback hook in this example so here we have just created this new function using this Aro function so instead of this let's add use callback select it so use callback has been imported from react you can type it manually also use callback from react and in this one we have to provide two parameters that will be one function and one dependency so in this function let's add one Aro function okay again we are passing this AR function we will add one comma and here we will add the square braet where we can add the dependency now what will happen this use callback will not create another function it will use the catched function whenever it will create this function first time and it will catch that function in the memory and whenever the renders happen it will use that cached function so the function will be same and when the function is same so this header props will be same there is no changes in this header props so when the prop is not changing then headed will not rendered again let's see if I refresh this click on this button you can see the counter is increasing it means the state is changing and this header is displayed here but this header is rendered only once it is not rendering so we have fixed this problem using the use callback hook now let's come back to the code and see when this use callback will create a new function so in that case we have to provide any dependency here suppose we will provide this count like this provide this count in parameter so whenever we click on the button this count is changing so whenever the count will change it will create a new function right because this count is changing so it will create a new function so the new function will be passed in this header so every time it will pass a new function it means the props will be changed in this header so header will be rendered again let's test it refresh this web page click on this button you can see the rendering is happening right here it is increasing the value let's see if I click it becomes seven so rendering is happening because we have added the count so whenever this dependency is changing it is creating new function and when we remove this dependency it will not create a new function it will use the cached function so the function will be same and this props will be same so it will prevent this header component for Unnecessary rendered so this is how we can use use callback hook to store the function in catch memory now we will learn about use context hook use context is a react hook that allows you to access data from any component without explicitly passing it down through props at every level or we can simply say use context is used to manage global data in the react app so let's understand why we need use context so let's see this example suppose we have created one application where we have a footer and in this footer we have to display the phone number and here we have a profile area or profile component and in that profile component we have another component which is contact and in this contact component we have to display the phone number right so we have to pass the phone number in footer also and in this contact component also and this context component is inside this profile component so where we will add this phone number data so we will add this phone number data or phone number variable in this app component right so we have declared the phone number in this app component so from this app component we can directly pass this data in this footer using props right but when we have to pass this data to the contact then we have to first send this data in this profile using props first we will send it in the the profile component and from this profile component again we will pass it through props in the contact component now we can display the phone number in this contact component so here you can see we are not using the phone number in this profile right but still we have to pass the data in the profile component then again pass the data in the contact component right we are not using the phone number in this profile but still we have to pass it so whenever we have to pass the data in the react app we have to use the props and using props we have to send the data at every component level but this would be very painful when we are working with more nested components like you can see this context is nested inside this profile so when we have more nested components it will be very difficult to manage the data and we have to pass the data through to each component level to solve this problem use context was introduced that allow us to create global data and we can access these data from any component without passing it through props at every component level we can use the use context hook in three simple steps first one is creating the context the second step is providing the context and the third step is consuming the cont context so let's start with the first step that is creating the context to use the use context hook we have to create the context first so in the SRC folder we will create a new folder with the name context and in this context folder we will create a new file and the file name is app cont text do jsx the file name extension should be do jsx now in this file first we have to import the create context so let's add import create context from react like this here we will add const then app context equal to we will use this create context so now we have created this app context using this create context right here we have to export this one so let's add export next we will create one provider function so just add const let's add context provider it will be one Arrow function and in this parameter we will pass props and here let's add return so it will return this app context so just add this app context do provider function and let's close it so we have added app context. provider and in this one we will add props do children like this and here we will add value and this value will be returned to the components where we want to send the data using this context so here let's add const we will add phone and let's declare one phone number so here we have added one phone variable so we can pass this phone variable using this value and now we can access this phone in any other component but before that we have to export this context provider right so here let's add export default context provider so let's understand it again here we have imported the create create context from this react library and we have added app context using this create context after that we have created one provider function which is context provider and in this one we can declare any data so here we have declared the phone number and using this app context. provider and this value we can pass these data in other components so we are passing this phone number in this value like this so we have completed the first step which is creating context now we will do the Second Step which is providing the context now we will add this context support in our react project to do this we have to open the main. jsx file and here we have this app component right here we have to wrap this app component using the context provider that we have created here we have created this context provider so using this we will wrap this app component so let's add a space here we will add context provider close this one and here we have the closing tag let's move it here after this app like this so you can see this context provider has been imported from this context folder app context. jsx file so you need to add this import a statement also so now we have added the support of this context in our react app so now all the components inside this app component can access the context data now we can use this context in our components so let me create multiple components first so here we have the components folder and in this folder we will create a new component which is foter do jsx and RFC and here we will add the text footer so we have creaded the footer component let's add one more component here so new file it is profile profile. jsx RFC and here we will add text profile let me add one more component this is context contact. jsx R fce and here we will add the text contact next we have to mount this profile and footer component in the app component so open app.jsx file and here let's add profile select it so you can see the statement import profile from components profile close this one now we will import the footer also so we have mounted this footer component you can see the footer import statement here after that if I open the web page you can see profile and footer so the profile and footer has been mounted on this app component now inside this profile component we have to mount the contact right so let me open this profile and inside this profile we will Mount the contact component close this tag so we have mounted this contact component and imported this contact from this contact let me save the changes and open the web page so you can see first we have profile and then we have the contact and then footer next we have to provide the phone number in this footer and in this contact right so let me open contact and here we will add H3 phone right here we will display the phone number and in footer also here we have footer so just add S3 phone right let me open right so we have profile contact footer and in the contact we will display the phone number and in footer also we will display the phone number so after creating this next we can use the data from our context so let's see the third step which is consuming the context so let me come back and uh first let's open this footer we are on the footer so here we have to use the context data so let's add const phone equal to use context and we are using this use context this is required for consuming the context so while creating the context we have used create context and while consuming the context we are using use context and you can see the use context has been imported from the react now in this use context we have to provide the name so the name is app context right we have created the file name app context and here we have the app context so let me copy this one and paste it here let's add like this app context so now the app context has been imported from this context app context file so we have to import use context and app context also like this next we can use this phone simply add this with curly bres save the changes and now you can see the phone number is displaying in this footer right so from our context file we are accessing the data in this footer component now I want to display the same thing in the contact also so let me open this contact and here also we will repeat the same thing we will add const phone equal to use context use context has been imported and in this use context we have to provide our context which is app context so the app context has been imported now we can use this phone in this S3 write curly Braes and use this phone you can see the phone number in this contact also so by using this we can directly display the context data in any component we don't have to pass it in the profile right you can see this contact is nested inside this profile but we are not passing the data in this profile profile component we are directly passing the data in the contact component right suppose we have to pass two data let me open this one app context and here we have declared one data right and here I want to declare one more let's add const name equal to greatest stack now we can pass this name through this app context provider so we have to pass this name here like this but it will not work we have to send multiple data in the form of object so let's add another curly bres like this so now we are passing one object where we have the phone property and name property right and wherever we are consuming this data like in this footer so here we have to add this in the curly bres now it will work and in this contact also curly bres now you can see it is displaying the phone number now we'll display the name also so in this contact let's add name and here we will get the name from our context so in this curly Braes we will add name we will get this name from App context simply put this name here save the changes open the web page you can see here we have the phone and name greatest tag so like this you can pass any number of data you can pass the variables you can pass the function and you can pass the state variables or any data so this is how we can use the use context hook to manage global data the context API can be used to share any type of data including objects functions and arrays this makes it a flexible solution for variety of Estate Management needs most common use of context API is to share the current theme of your application with all components or to share the authenticated user with all of our components in our application or to share the result of an API call with all of our components in our application that will reduce the number of API calls so this was all about the use context hook in react now we will learn about use reducer hook use reducer is similar to use a state but instead of providing a state and Setter function it provides a state and dispatch function the used reducer hook accepts two arguments first is reducer function and the second one is initial State and it Returns the current state and dispatch method so its first argument reducer function is the function that specifies how the state gets updated let's understand this hook with an example so here we have created one simple counter you can see we are displaying the count in this H1 then we have two buttons and we have created this counter State using the use State Hook and the initial value is zero and here we have added Setter function set count that will increase the value by one and this decrease button will decrease the value by one let me show you the web page also you can see here we have this counter if I click on this increase button the counter value is increasing and if I click on decrease button it is decreasing the counter value now we will create the same counter functionality using use reducer hook so first we have to import the use reducer from deact so let's add import use reducer so we have imported use reducer from react now we can use this use reducer hook so let's add it here and this use reducer accept two arguments the first one is reducer function and the second one is default state so here let's add reducer that is the function and here we will add the second parameter that is the state so here we will add the initial State let me remove this previous state which is count that we have created using user State we will remove this one and here here we have added user State reducer and state so here we can directly provide the state like this we will add count zero like this we can provide the initial State and this is the reducer function or we can also declare it here like We'll add const initial state equal to this object and provide this initial State here this use reducer returns one aray same as use a state hook so let's add const then one array and in this AR the first value will be state so this use reducer will provide a state and the second value will be dispatch method so just add dispatch when we use the US state hook we get the state and one seter function but when we are using use reducer we will get a state and dispatch method so for this use reducer we have added the initial state that is here next we will declare this reducer function so we have to declare this reducer function here before this line so let's add const reducer equal to and this reducer function accept two parameters the first one is current state and the second parameter is action like increase decrease Etc so the first one will be State and the second one is action and it will be one Arrow function now this will return the updated state so here we have the initial State and the count is zero so we will update this estate just add return and provide this one and here we will return the updated value so just add state do count + 1 why we are adding a state do count because from this use reducer we will get the state here right and in this state we have the object with count property right so to access this count we have to write a state do count so we are adding a state do count and we are increasing the value by one like this now we can use this state. count to display the counter on our web page so instead of count we will add estate. count so it will display the current count estate on the web page and now we have added this estate here and to update this estate we can use this dispatch method so just copy this one and instead of this set count let's add dispatch that's it let me add this one in the second button also right so whenever we will click on this button this on click property will call this dispatch method and this dispatch method will update this state how it will update it will call this reducer function and this reducer function will add one in this current state right let me save the changes and open the web page you can see if I click on increase button it is increasing the value y1 let's click again it is increasing and if I click on this decrease it is also increasing the value right because we have just added the reducer function that Returns the updated state with + one right now in this dispatch method we can provide the action also so here we can write type and uh in this type we will provide increase like this we have to provide it in curly process so with this dispatch we are providing the type increase and in the second one we will provide the type decrease like this and now based on this type this reducer function will calculate the different return value so instead of returning this we will add the switch case right and that switch case will work on this action here let's add one switch a statement and let's take this action DOT type and based on this type we will add different cases so let's add case and if we will get this increase so when the case is increased here we will add the return statement so let's provide this one so when the action is increased it will return this one return count and it will increase the count value by one now we will add the second case here we have to provide the colum now let's provide the second case it will be decrease here also we will return the state and it will be minus1 now we will add the default case so just add default here we will return State that's it so what will happen when we are calling this dispatch method and we are providing a type increase then it will call this reducer function and uh from this switch case it will execute this line because the case is increased so it will return the count + one then if we are providing type decrease then it will provide the count minus one and if we are not providing increase or decrease then it will return the default value and it will return the current state let me save the changes and open the web page so refresh it you can see if I click on increase it is increasing the counter value and when I click on decrease it is decreasing the counter value it is working fine now let's understand this example again so what we have created here first we have imported this use reducer from the react library after that here we have created the initial State and in this initial State we have added one object where we have stored the count zero right next we have added this reducer function in this reducer function we have added different return based on different action if the action is increase we are increasing counter + one if the action is decreased we are returning counter minus one and here we have declared this use reducer in this use reducer we are providing the reducer function and initial State this use reducer will return one array where we will get the state and dispatch method so this state will give the current state value and this dispatch method is used for updating this state so we can use this state to display the state data anywhere so we are using state. count because in this initial State you can see we have the object and the property name is count so we are using state. count now for updating this state we can use this dispatch method so we are adding dispatch right and in this dispatch we are providing the type and based on this type we will get the result we can add more acction types in which we can pass the data in action as payload and we can operate on that data let's take an example here we will add one input field input type will be number let me open the web page you can see here we have the increase decrease and one input box let me add BR so this input field is here below these buttons right now after adding this input field in this input field we will add this dispatch method so here let's add onchange property and we will add one addo function and in this one we will provide this event and here we will add this dispatch and in this dispatch we will provide different action so let's provide type and the type will be input like this let me add it in the new line so you can see clearly so in this one we are adding dispatch and in the previous buttons we are adding type increase type decrease and in this one we are adding type input and with this type input we can pass one more thing so let's add comma and we'll add payload and in this payload we will add event. Target dot value so whatever value we will input in this input field we will get that value here and we will get that value in string so let's convert that value in number so just add number and add this e. target. value like this now in this input we'll add one more thing that is value and this value will be state DOT count so the count value will be displayed in this input field let me open the web page you can see the three is displayed in this input field if I click on increase here you can see four and in this input field also you can see four let me zoom in the browser now you can see clearly if I click on decrease this three is displayed here but right now we cannot update this value so now I want something like when we update this value it should update this count for the let's come back and here we have provided on change and we are calling this dispatch and in this one we are passing this payload so using this input type and payload we can update the state so here we'll add one more case duplicate it and let's add the case input because we are passing the type input right so in this input we will add count and it will be action dot payload so from this action that is here it will find the payload value and that will be added in this count and it will return this object let me save the changes and open the web page now you can see if I change the value in this input field let me add 50 so the 50 is displayed in this counter if I add 100 it is displaying 100 and when we click on decrease it is decreasing the value in this counter also and in this input field also and it is also increasing the value so this is how you can use the use reducer hook to manage the estate when we use the use State hook we directly update the state variables using the seter function but when we use the use reducer hook we can efficiently update the state variable for different action so this is all about the use reducer hook in react now we will learn about use layout effect hook use layout effect works similar to use effect but it is called before the user interface gets mounted it means the use effect gets called after printing the Dom element but use layout effect gets called before printing the Dom elements for example if you create a layout using Dom elements and want to change the layout color using the use effect hook then first it will display the Dom element and and after that it will change its color that will cause a blink or flickering issue but when we will change the color using use layout effect then first it will change the color and after that it will display the Dom element on the web page let's understand use layout effect with an example so here let's add one use effect use effect has been imported in this use effect we will add one function and in this function we will log one message so let's add a message message from use effect and here we will add comma and a square bracket now let me duplicate this one and here we will use the use layout effect select it so use layout effect has been imported from the react Library here we are adding use layout effect and in this one we have a function and one dependency array and here we have one console log message so in this one we will add this message message from use layout effect that's it now in this return let's add one text in S2 let me add test message so after that if I open the web page you can see here we have this test message and we will open the console tab so in this console you can see first we have the message message from use layout if effect and the second one is message from use effect but if I come back to the vs code you can see first we have added use effect which is here we have added use effect and after that we have the use layout effect but in the console it is printing this message first and after that it is printing this message let me show you the console again you can see message from use layout effect and after that we have message from use effect so now you can see the use layout effect is executed before this use effect and this use layout effect is actually executed before printing this S2 so first it is calling this use layout effect and after that it will print this Dom element which is S2 and after that it will display this message in console which is use effect because this use layout effect is called before mounting this UI element and this use effect is called after mounting this UI element right now if I refresh the web page you can see it is printed very quickly so you can't see the difference so let me add some calculation here that will take time to print this UI element so let me add one add aray in this array I'll add 40,000 and fill this array with empty string and on this one we'll add the map method we will map each element of this array in this map we will add Arrow function and here we will add individual item and index and here we will print the LI tag right and in this Li tag we will display random numbers so first we will insert this index in this Li so just add key index let me add it in new line like this now in this Li tag we will display the random numbers so just add math do random and uh after that we will add the power 10 of this random number so it will be a heavy calculation so let me add like this math. power and inside this one we will add math. random comma 10 so it will generate one random number and it will add the power 10 and it will be printed for 40,000 times so this UI rendering will take time so now we can see the difference so first it will print this message message from use layout effect after that it will print this Li elements where it will print random numbers for 40,000 times and after that immediately it will print this message from use effect so let me save the changes and open the web page you can see first it prints this message message from use layout effect after that it prints this random numbers and after that it will print this message message from use effect let me clear the console refresh this website again so here we have the message from use layout effect after that it will update this here now we have different random numbers and after updating this UI it is displaying this message from use effect you can see here we have the number 5124 like that if I refresh the web page let me clear the console refresh the web page first we have this message after that it is updating this random numbers and after that it is printing this message which is message from use effect so now you can clearly see use layout effect is called before rendering the UI element and this use effect is called after rendering the UI elements we can use the Ed layout hook for measuring Dom elements and for animating the elements and for fixing the flickering issue and we can also use it for API calling but react official document says use layout effect can hurt the performance of app that's why it is recommended to use use effect Hook when possible so this was all about use layout effect hook in react now we will learn custom hook in react react allow us to create our own hook which is known as custom hook so why we create a custom hook let's suppose you have a component logic that need to be used by multiple components so we can extract that logic to create a custom hook let's understand the custom hook with an example here in this app component I have added one input field and then we have one title in S2 here we are displaying hello and the name and this name is coming from this state variable we have name and set name and we have created it using the US state here we have added the use effect in this use effect we are adding local storage do set item with the key username and value is the name this name is coming from this state and it will be executed every time when this name changes because in this dependency we have added the name state so it will update the name in the local storage data in the browser now what is happening here here we have added set name and in this set name I have added this e. target. value it means it will set the name using this input field value so whenever we'll add the new name or change anything in this input field it will update this name State and it will update the name in the local storage using this use effect so this logic will update the data on the local estor of web browser and this use state will get the data from the local storage whenever we will reload the web page so here we have added the Turner operator it will search for this local storage get item we are adding get item so it will find this local storage with this key key is username so it will find the data in the local storage with the key username if it it is available it will set that one in this name if it is not available in that case it will add empty string in this name right so let me show you this on the web page you can see if I reload the web page here we have the input field and here we have the hello and there's no name here but if I open the dev tool click here go to application and click on this local storage then click on this Local Host so here you can see one key which is username because this use effect will add one data in the local storage with the key user name and in this name it will add this empty string right now if I add some name here let me add greatest tag so this Greatest Tag is displayed on the web page also and it is saved in this local storage with the key username so the username is greatest tack in this local storage now when we will reload the web page you can see this great St is displayed here because when we reload the web page it will find the data in the local storage and if the username is available it will display that here using this turn operator it will find this local storage G items by username if it is available it will display the data and if it is not available then it will display empty string so this logic is working now suppose you have to add one more State like this you have to add ID then again you have to create one state like this then you have to add the use effect right or suppose you have to use this local storage set and get functionality in multiple components then in the multiple components you have to write this code so to solve this one we will use the custom hook where we will add these logic and we can simply use that in different component right so to create a custom hook we have to add the hook name and that will start with use for example use State use effect so like that we can add any name like use fetch so let me create a folder in this SRC and write the folder name hooks and in this folder we will create a new file and the file name will be use local storage because we are adding the local storage functionality so the file name is use local storage. jsx here we will add R fce like this now let's come back and let's remove this logic we will cut it from here and paste it in this one like this now we can use this use local storage in another component so whenever we will call this use local storage we will pass some arguments so here let's add the parameter key that will be stored in the local storage and with this key we will pass the initial value also so let's add initial value now instead of this username we will provide this key so remove this and provide key like this so it will search the local storage if any data is available with this key then it will display the data or it will display the initial value so let me copy this initial value and paste it here like this so this will retrieve the data from the local storage and this use effect will set the data in local storage so in this one we will provide this key here and here we will add key so this use effect will be executed whenever the name State changes or whenever the key changes this will execute this use effect that's it and here we have return a statement so in this one we have to return one array and in this array we will return this state which is name and we will also return this set name that's it save the changes now our custom Hook is ready in this custom hook we are accepting two parameters key and initial value and using this key it will retrieve the data from the local storage and using this key it will store the data in local storage by using this line local storage do set item key and this name name is here and after that it will return the updated estate name and this set function set name now we can use this custom hook which is use local storage just copy this one open app.jsx file here we can remove this use effect use state it is not required now and here we can use our custom hook so let's add use local storage it is here so the use local storage has been imported right now in this one we have to provide the key and initial value so let me provide the key using name and the initial value will be empty string and here it will return two value the first one will be data from the local storage and the second one is seter function so let me store it in one add a so the first one is name and the second one set name like this so this name will be displayed in this title and this name value will be added in this input field also and this set name is used here in set name that will update the data in the local storage let me save the changes and open the web page so here we have some error let me come back and open this local storage you can see in this one we have used use State and use effect and we have not imported it so just we have to import it from react use a state and use effect that's it save the changes open the web page now we have the input field and message greatest tack let me clear this so you can see the local storage is clear here there is one key username and the value is empty if I refresh it still the value is empty if I type something you can see the same value is saved in this local storage with the key username and the value ainash Let me refresh it still it will fetch the data from the local storage and display it here so now you can see we have added this local storage feature using this single line that's it now suppose I have to add one more data in the local storage so how we can do that let me add the same line again and we will store ID and this will be set ID and uh here we will add user ID and initial value will be empty and uh let me display this ID on the web page so duplicate this here we will add the input field enter your ID let's add value ID and here set ID Setter function set ID and here we will update the message your ID and provide this ID State that's it so we have just used this ID and set ID in this element and added this single line that uses the custom hook and we are providing the key and initial value that's it if I save the changes open the web page you can see we have another input field right now the data is empty in this input field and your ID and the ID is empty so now if I type something 1 2 3 you can see this 1 123 is stored in this local storage with the name user ID and the value 1 2 3 and here it is displaying your ID 1 23 remove this comma now it is looking good if I reload the web page still we have this because when we reload the web page it will fetch the data from the local storage and it will display it in this input field and in this title also so now we can use the local storage feature by using this custom hook we can use this use local storage custom hook in any component this is how we can create and use the custom hook in our react application now we have completed almost commonly used react hooks I hope this video will be helpful for you if you have any question you can ask me in the comment section please like and share this video and also subscribe my channel great stack to watch more videos like this one thank you so much for watching this video
Info
Channel: GreatStack
Views: 58,517
Rating: undefined out of 5
Keywords: react hooks, hooks in react js, useeffect react hooks, usecallback react hooks, usecontext react hooks, react hooks tutorial, usememo react hooks, usereducer react hooks, custom hooks react, hooks in react, use ref in react hooks, custom hooks in react js, react hooks explained, react custom hooks, react js hooks
Id: 6wf5dIrryoQ
Channel Id: undefined
Length: 137min 47sec (8267 seconds)
Published: Thu May 16 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.