React Hooks in ONE Video 2022 [ EASIEST Explanation ] | React JS Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this tutorial we will see all react hooks in a very simple way after completing this tutorial you will know all about hooks and how it works so let's don't waste time and get started before we dive into used it hook let's understand first what is hooks if you already know you can skip this part and directly jump on you straight hook so what is hooks hooks are the functions to use some react features in functional components in other words we can say that hooks are functions that make functional components work like class component i know this sounds complicated but it's not let's understand with one story before react launched hooks there is only one way to use state and life cycle methods by using the class components now developers had some problems with class components so react takes some time to develop special functions that we can use in functional components and that special functions are called hooks so i think now you understand what is react hooks which are functions that make functional components work like class components let's start with our first hook which is used hook [Music] what is u-state hook u-state hook is a function to add state in functional component now you might ask what is state so state is nothing but just values or variables of your component in other words all variables in your component are called as state of the component so whenever you want to create a variable then you have to use u-state hook simple as that let's understand with the example here i have new react application and i deleted all unnecessary files from this so first let me create a functional component by using rafce this is the amite for creating the functional components but you need to install this es7 react extension first i love this extension it boost my productivity in react now here i am going to create one simple counter which displays a counter value and one button called increase and when we click on this button counter value will increase by 1. now this is where i want to display the value of the counter so we need state and this is where we use use state hooks so to use any hook first we need to import that hook from react library so right here used it okay here we are going to call use it function and we give our counter initial value like zero now this function is going to return an array so let's console it see this array has two elements the first element is our original value which is 0 and the second element is one function so let's store this first element in the counter variable and display it here by using curly brackets save the changes and take a look we get our counter now the second element of this array returns a function and by using this function we can update our state values so let's store this element in variable called state counter now whatever value we pass in this function will be the value of this counter variable let me show you that here we want to increase the counter by 1 when we click on this button so add function in one click increase counter now we need to define this function and inside this function we write set counter original value which is counter plus 1. save it and take a look see it works and when we refresh the page it again starts with 0 which we pass in that function of your state now here our code looks little bit ugly so we always use the shortcut for these three lines which is called array destructuring so here at the place of array add square brackets and inside that write the first variable name which is counter and then write function name which is the set counter now we don't need these two lines it works the same as before and our code looks clean and you can use multiple use state hooks in a single component now let's see how we can use the use state to get value from the input so let's create one input with type text here we need to handle the on change event and we pass the expression and arrow function and we use e dot target dot value to update state variable so type used it here and here we can give our variable initial value in this case empty string now whenever the value of this input field changes we call set name function and pass e dot target dot value so we call set name and pass this value now let's change our label to variable name has clicked variable counter times save the changes and take a look here we have text box and when we write name code it's immediately updates here and also counter updates on click now let's see how to use use state hook when we have object as a state variable so here we create two state variable which are counter and name now we can do same with one state variable which is object so create new used it and pass object as initial value counter to 0 and name to empty string now define its name by using added structuring details and set details now delete these two lines we don't need them so instead of writing name write details.name and details.counter so here in increased counter function i remove this and guess what should we have to add right we have to add set details function for update that counter value so i write set details and remember whatever value you pass inside this function it will be updated with the original value so object counter colon details dot counter plus 1 save it and take a look yep it works but there is a one big problem that we don't have our name element inside this object let me show you that so i simply write here console.log details and save it now refresh the page and see first we have two elements in object now when i click on this increase button the name element is removed from our object so why does that happen it happens because we directly pass object without add other old values so the solution is first we add all other values of that object which is name here and just update that counter element with new value so inside details function we can pass another function and that function can return the previous value of our state variable don't get confused just to see this so this previous is same as this details variable let me show you that i console it and add some text here see we get all values when we click on this button with error because we can't write console inside this function so remove that and now we use the spread operator by using three dot previous this will add all previous values of that state variable now we replace counter with old value which is previous dot counter plus 1. save the changes and take a look see it perfectly works with the name element so whenever you work with an object or array we have to first add all previous values by using this method and then update whatever we want to update let's recap what we learned so use state is used to create state variables in functional components so to use u-state hook we need to first import that and use it inside the functional component here you can pass any type of data like boolean number text object array anything and then store it by using added structuring the first variable is its current value and the second one is the function for updating that value simple as that some people can get a little confusion and i was also confused when i learned you state hook for the first time but with practice i learned this concept and use that in my projects [Music] use effect is used to perform side effects in our component so what is side effects side effects are actions which are performed with outside world we perform a side effect when we need to reach outside of react components and do something for example fetching data from api directly updating the dom in which we use document or window object and timer functions like set timeout or set interval these are most common side effects in react so to perform any kind of side effects we need to use use effect hook let's see in example so here i created one state variable and its value will increase by 1 when we click on this button to use any hook we need to first import that hook from react library so i write here use effect and now we can use it in functional component so use effect hook except two arguments first callback which is a function in which we write our side effect logic this function is executed whenever something change in this component and second dependencies which is an array of variables and it's an optional argument in simple terms first argument is what to run and second one is when to run so use effect runs on every render which means that when the count changes a render happens and we can control that by dependencies if you're familiar with class components use effect is a combination of component date mount component date update and component will unmount let's see variation of use effect hooks there are only three variation of use effect hook first use effect without any dependencies second use effect with an empty array and third use effect with variables let's see first variation of use effect hook so write use effect and pass only callback function and in that function i want to update our web title with this same message so write document dot title equals to in backticks dollar count new messages and save it refresh the page and see whenever this component render use effects run and our title gets updated with our message now when something change in this component means we click on this button and it runs use effect hook and title changed with counter so when we use use effect hook without any dependencies use effect will run on every single change in that component in this case it's app component because we write use effect in app component now let's see use effect with an empty array so in this same example we pass an empty array in use effect dependencies and let's see what happen so save it and take a look refresh the page and see use effects run when component render now when we click on this button which means counter is going to change but the title is not updating on that change so when we pass an empty array in dependencies use effect will run only one time when our component gets rendered first time and after that use effect will never run it's useful when we use to fetch data from api or server and that will fetch data when component gets rendered first time by the way cheat sheet of use state hook is available in description now let's see the last variation of use effect which is with variables so to understand this concept i create another state variable name author count and button that will increase that counter by phi now i want to change title when we only change other count state for that we need to pass other count variable in that dependency array and i change this count variable with other count save the changes and take a look refresh the page and see it perfectly works on render now when i click on this other count state variable title is updating with this state but when we click on this old button it will not work because we pass our new variable independency array so use effect only runs when the state variable's value will change and you can pass more variables by using comma now the final part of this use effect hook is cleanup function and it's little confusing for beginners let's understand with another example so everyone can understand here i have used set interval function for countdown timer and that interval will not stop unless we use the clear interval function if we are setting state using set interval and that side effect is not cleaned up when our components unmounts or we are no longer to use it the state is destroyed with the component but the state interval function will keep running and that's make our application slow and low in performance so it's important to clean up these functions so to use cleanup function we need to run return function in use effect let me show you that so here in this use effect i write return arrow function and inside this function i write clear interval and pass the variable name of set interval function which is timer the cleanup function will be called when the component is unmounted it's difficult to see in this example so i create one counter and then update that counter on button click by one now i create a new use effect function with count dependency and write console.log run effect with count variable so when the count variable will change use effect runs and now i write return function and inside this function i simply console.log cleanup also with count variable for just getting the idea when cleanup function will work so save the changes and take a look refresh the page and it's working on first render now whenever this use effect run again old cleanup function will run first and then this callback function will run let's see this live so here it work for first render and when we click on this increase button which means this use effect will run so first cleanup with zero value will run and then callback function print for value 1. now again we click on this button first previous cleanup function will run and then callback run so cleanup function is not required in every case it is only required in a few cases such as when you need to stop a repeated side effect when your component unmounts simple as that let's recap what we learned so use effect is used to perform side effects like fetching data manipulation with document and window timer events like set interval and set timeout use effect accept two arguments first is for callback function and second is for dependencies which is optional in simple terms what to run and when to run and there are three variation of usb pack hook first without dependencies which means it runs with first render and also run on anything changes in that component second with empty array which means it runs only on first render and it's useful for patching data third with state and props which means it runs on first render and then any variable that we pass in dependencies change it will run simple as that timeouts subscriptions event listener and other effects that are no longer needed should be disposed with the help of cleanup function [Music] so what is use context use context hook is used to manage global data in react application like global state theme services user settings etc let's understand why we need use context hook so here is a situation imagine you create an application with this type of component structure so main component is app and then it has four child components and child components have also some child component so it's like a hierarchy of components now imagine we have user details in this app component and we need user details in this single post if we use props for sharing that details we have to first pass in main component then pass in feed then following post and then we get user details in single post component so it's very annoying and hard to maintain so use contacts will help us to create global data for our react application and we don't have to pass that data through all these components we can access that data in all component we needed now let's see how to create context so to create context in react requires three simple steps first creating the context second providing the context and third consuming the context so let's start with step number one creating the context so we are creating the global state for user logging so import create context function from react library this function is used to create context now right before your functional component create context and store that in variable called logincontext you can take whatever you want to now for step number two which is providing the context so after creating the context we need to define in which components we want to access this context so again in that hierarchy if we want to pass data to single post component we just need to provide the data to main component and that can be accessible in all their child components so in our example we want to access that data into main component and it has child component single post so write login context dot provider and add that component between this context provider whatever component you pass between this provider it and its style component can access this context value now we can pass value by using value attribute so write value equals to in curly brackets i simply pass true here now let's see how to access this variable inside our single post component so open that component in which you want to use that variable so to use login context variable we need to use use context hook so import use context hook from react library and inside this functional component write use context and it accept one argument which is that login contacts so we need to import that login contacts from our app component so let's first export that from app component and then import login contacts from app component now pass this login contacts inside the use context hook and we store this value in variable called login so let's console it save the changes and take a look see we get true so whatever value you pass in this context provider you can access that value by using use context hook if you understand these three steps congratulation you understand the use context hook let's quick recap what we learned use context is used to manage global data in react so we don't need to pass that data through props from first parent component to last child component if you want to pass data just for child component then you can use props don't use contacts everywhere just use it when you need it now to use use context you need to just follow three steps first create the context using create context and give name to that context like we did login contacts now second you need to decide which components can access this context with the use of context.provider and pass other components between this provider tag and in value attribute pass value inside curly brackets and last step you need to import that context from your file and pass that contacts inside use context hook and store it in variable simple as that now you see our app component looks a little bit ugly but it's a simple one context imagine if we have five or six contacts then you just don't like to code in that project and if you are working for company they also don't like unorganized code so let's make organized structure for creating context so first of all i create one new folder in source folder called context we create all context here in this folder now create a new file in that folder called logincontextprovider.js and in this file we save our all login contacts logic so first i create amit by using rafce and now i just copy this create context from app component and paste it here now in return we have to set provider so add logincontext.provider and inside that provider we have to pass all children so write in props children and pass their children inside provider now give a value attribute in provider and i want to pass state value for this context so i create user details and pass default value true you can pass any type of data and pass that state variable in value now back to our app component and import that login contacts provider and replace provider with login contacts provider because we pass children inside that provider and remove unnecessary things from this component now last and final step change this context path from app to our contacts slash login contacts provider and that's it we organize that ugly code into organized code [Music] so what is use rep usref allows us to access dom elements and also for creating mutable variables which will not re-render the component these are two most common use cases of use ref hook first let me show you how to create a mutable variable so in this example i create one input field and on change event i update this name state with the current input value and display the name here now imagine we want to count how many renders happen when we input the name when i teach this hook to my first students they ask me why we can't use usted for this and i think you might have the same question so let's see this live why we don't use u-state hook for count renders so first i create one more state variable and give name count and pass 0 as the default value now in use effect i will update the count by one for each render so i write set count previous arrow function previous one and after name i will display count variable now save it and take a look see count is constantly updating because when this component is rendered it will update discount variable by 1 and because that state variable is updated the component is rendered again and again so we are stuck in an infinite loop because we use u-state so let's solve this with a use ref hook so i remove this state variable and use effect and import use ref from react library now write use ref and here we can give default value same as used it now this function returns an object with one property that is current so let's store it in variable count and let's console this variable see we get object with one current property we can update or show this value by using count dot current property so here write count dot current and save the changes now let's update this value when component rendered so write use effect count dot current equals to count dot current plus one save it and take a look when we type in input box count is updating by one so first use case of use ref is to create a mutable variable without causing re-render now let's see the second use case of usedrep which is accessing the dom elements so in react we can add a ref attribute to element for access it directly let's understand with the example so here we have one input box and button and when we click on this button this function will execute now i want to change the width of this input when we click on this button we can do that in vanilla javascript by using document.getelements by id or by class name but in react we don't need to do that we directly use use rep and we get that element in variable let me show you that so first import use ref hook and write use ref and store that in variable now give this input one property ref equals to input element which is the name of our ref variable now let's console current value see we get that input field in the current property now i am going to change this input width to 300 pixel so as we do in vanilla javascript write input element dot current dot style dot width equals to 300 pixel here input element dot current is our input field so save it and take a look see when we click on this button input width is increased to 300 pixel now let's focus on this input when we click on this button so back to vs code and in the same function i have to add guess what right input element dot current focus so save the changes and take a look when we click on this button input width will increase and input is in focus so it's the same as we do in vanilla javascript just use input element dot current and after that you can access all javascript methods for the element now some of you might ask how can we know which methods we can use with elements and how can we remember it so the answer is you don't have to remember any method name let me show you my trick to see all the methods we can use with elements so here simply remove this current property and save it now in console you can see this input element object with current property now click on this little arrow and again click on this arrow so here you can see all methods which we can apply on this element for example we want to apply style so scroll down to the bottom and click on this icon to see more property and here you can see style property click on it and you can see all styles property simple as that so let's recap what we learned use wrap is allow us to create mutable variables which don't cause re-render and it is very useful to access dom elements without writing document.getelement by id or by class name so here is a syntax of use ref hook here we can pass the default value of this variable and it is optional this variable has one object and that object contains only one property which is current if we want to access or update it we have to use variable dot current we can also access elements by using the wrap attribute and remember my trick with the help of console we can see all methods [Music] so what is use reducer use reducer is used to manage state in our react application in other words user reducer works like a state management tool now you might ask what is state management so state management is used to manage all states of application in a simple way or to write simple and clean code for all states and always use the use reducer hook when you have a lot of states and methods to handle so let's understand use reducer with the example here i created one simple counter application using the use state hook so we have one counter variable and two buttons increase and decrease so when we click on increase button count increase by 1 and if we click on decrease button count decrease by 1 very simple example now let's apply use reducer in this example so first of all let me clean this state variable now import use reducer hook from react library and in functional component write use reducer so use reducer accepts two arguments the first one is reducer function which will manage all states and the second one is our default state for now forget about this reducer function we will see this after explanation now let's first define our default state so i am going to create one object in which we can define our all states so write initial state equals to in object we want count variable so count colon 0 now pass this initial state here so this use reducer returns array same as use state hook which means first element will return current state and second element will return a function which will help us to update that state so let's use added structuring for storing this variable so we call first element as state and second one is dispatch it is the most common name for use reducer if you want to take another name you can take that it's totally up to you now let's define our reducer function which is the most important part of use reducer hook so inside this function we will write our all logic for this use reducer so this reducer function has two parameters first parameter is state which means where our application is currently at and second parameter is action which means which action we have to perform for example increase decrease etc i know this is little confusing but after completing full example you will understand it properly now this function will return the updated state so for now i am just returning the object with count and current count which is this state dot count plus one now to call this function we will use dispatch function so here in increase count function i just call dispatch and pass nothing inside it now i am deleting this set count and here i write state dot count now save the changes and take a look see when we click on this increase button count is increased by 1. now let's see how to call different actions like increase and decrease so first we pass object in dispatch function with type property colon increase now we have to handle this type in this reducer function so let's lock this action parameter so we know what we get save the changes and take a look when we click on this increase button we get object with type property so whatever we pass in this dispatch function we can access it by this action parameter so let's use a switch case to manage different different actions you can use if else as if but i like switch case so write switch and pass here action dot type and inside it write first case which is increase and in this i return this now for second case which is decrease we return same count but -1 and at last we pass a default case and return the same state so if we pass any other type except increase and decrease this default value will run so in decrease count function we write guess what write dispatch in object type decrease save the changes and take a look see it's working fine so let's recap what we learned use reducer is used to manage complex states in react application so here is a syntax of use reducer hook it takes two arguments first one is reducer function in which we write our all logic and second argument is initial state which is object of all variables now this hook returns an array with two elements so we use added structuring first element is for access current state which is our initial state and second element is dispatch for updating that state simple as that now we define reducer function which has two parameters first one is used to access current state and second is an action which used to get different different actions so whatever we pass in this dispatch function we can access it in reducer function by this action parameter and then with the use of switch case we can perform different tasks that's it now in this example i did little mistake by using type in string so we have to take care of its spelling mistakes in two different places so instead of this we can create one object with name action and we always use all uppercase for this action object so whenever we see that we know it's for reducer so in this object first i create increase for increase and decrease or decrease now at this place i replace it with action dot increase and accent dot decrease and in dispatch also we write action dot increase and action dot decrease so now there are no chances for spelling mistakes and if we want to change one name we can directly update in this object and in other places it updates automatically now i want to cut these three variables and paste it at the end of this component so our code looks clean and easy to read [Music] so what is used layout effect the use layout effect works exactly the same as use effect but the difference is when it's run so use effect runs after the dom is printed on the browser but use layout effect runs before the dom is printed on the browser so whenever we want to run code before the dom is printed like we want to measure an element's height width or anything related to layout we can use use layout effect and it runs synchronously which means it runs the first line and only move to second line if first line execution is completed the most common use case of use layout effect is to get the dimension of the layout and that's why its name is use layout effect first let me show you when it runs so in this example there is one toggle button which toggle this text and one use effect with dependency toggle so this use effect will run when this toggle state will change and print use effect in console first i import the use layout effect from react library and now i duplicate this code and replace use effect with use layout effect now save the changes and take a look see when component gets render both hook will run now when i click on this toggle button again both hook will run but focus here use layout effect is always runs first now you think it's because we write it before you state so i move use layout effect after the use effect hook and take a look see use layout effect will always run first so the workflow is first react calculate all this component and then use layout effect will run then react prints all elements on the dom and at last use effect will run but this process is very fast and that's why we can't see it live so 99 time we use use effect in our project if user effect is not working as we want only then we try use layout effect now let's see most common use case of use layout effect so in this same example i want to get the dimension of this text and then we add padding top as much as its height so for access dom elements what should we have to use right it's use rep so i create one user f and vs code auto import use rev from react and that's why i love this es7 extension it's a great productivity tool for react developers now we store this use ref in constant called text wrap and pass the ref attribute to this text now we first try to use use effect and comment out this use layout effect so in use effect we write text ref dot current dot get bounding client rect by using this function we can get all dimension of this element let me show you real quick so first of all store this in variable dimension now let's console it and take a look and we get error because we have to add one condition to check if this text wrap is not null only then we have to run this code so write if text ref dot current not equals to null and move this code inside it save the changes and take a look see we get the dimension object with all properties now i want to add padding top for this text as much as its height so write tax ref dot current dot style dot padding top equals to in backtick dollar dimension dot height pixel and save it see when we click on this toggle button first this text shows here and then it moves to the bottom see in the slow motion now this is the problem with the use effect we see this friction in output now i replace the use effect with use layout effect save the changes and take a look see we didn't see that friction because use layout effect runs before the dom printed so let's recap use layout effect use layout effect is the same as the use effect hook but the only difference is when they run so the workflow is positively calculate all mutations then use layout effect will run and then react prints all elements on dom and after that use effect will run and the second difference is that use layout effect is synchronous and use effect is asynchronous so 99 time we use use effect in our project but if that use effect will not work properly only then we use used layout effect and i show you the most common use case of use layout effect [Music] so what is use memo use memo hook is used to apply memoization in react so what is memoization memoization is a technique for improving the performance of code and it is useful to avoid expensive calculation on every render when the returned value is not going to change let's understand with the example so in this example i create two state variables number and dark number is for input and pass that number in this expensive function which i declare after the component so basically this function will return the same number but after running this unwanted loop which i created just for explanation in real world it can be any long calculation or anything that takes more time and then store its return value in calculation variable now this dark state is for total dark and light mode and according to this dark variable we change the background color and text color let me show you so whenever we increase the value of this input that expensive function will run and return the new value in calculation and print it here and when i click on this toggle button background color and text color will change now focus on this calculation whenever we change this number we are calling that expensive function and console this loop started but it takes 0.5 or 0.3 seconds delay for updating that's because of our unwanted loop inexpensive function but when we click on this toggle button it also takes some second to update the theme and you see console again prints loop started and that's why we face this delay in toggle theme so when we click on toggle button react is re-rendering the component so first this line will run and it calls this expensive function and that takes extra work and we can't immediately toggle the theme so the solution is we will only run this function when this number is changed so we use the use memo hook for that and the good news is use memo syntax is same as use effect hook so first i import use memo from react library and add it in functional component so use memo will take two arguments first one is for callback function and second one is for dependencies array so whenever any variable from this dependency will change only then and then this callback function will run so i pass number in this dependency array and inside this callback function we call this expensive function and pass number as parameter now you think what is the difference between use effect and use memo so use effect and use memo is same but the difference is in use effect we can't return the value and we can't store it in variable we have to create one more state variable and then with the set value function we can update that but in use memo we can return the value and we can store this value in variable so i store this value in memo calculation now i remove this line and at the place of calculation we call memo calculation now save the changes and take a look when we change the number it takes some seconds and that's obvious because we add unwanted loop but when we click on this toggle button it's not taking the extra seconds and we can immediately toggle themes and this technique improve the performance of our application which is very important thing in today's world let's recap what we learned use memo is used to improve performance of our react application and we can stop running unwanted functions on re-rendering so here is a syntax of use memo hook it takes two arguments first one is callback function which will return the value and here we will store this value in variable now second argument is dependency array in which we can add variables and when this variable will change only then and then this callback will run and with this variable we print the return value so we perform all side effects in use effect hook and all expensive functions calculation in use memo hook simple as that [Music] so what is use callback use callback is used to return memoize function and it's also useful for preventing functions being recreated on re-rendering i know this sound little confusing but it's not let's understand with the example so in this example i create two state variables first one is the number for number input and second one is for toggle theme and according to that our background color and text color will change now we have one function called calculate table and it returns the first five rows of that numbers table in real world it can be anything like calling api now here i created one simple component called print table for printing the table and i pass this function as props so in this component i create state rows and in the use effect i console this line and pass this calculate table function inside rows function so that values of array set in rows variable and then print this rows array using this map method simple as that let's see this live here we have one input for number and after that i print this table using print table component and at last we have toggle button for toggle theme so when we click on toggle button theme will change and when we change number we see its table below now i will show you the problem first of all let me open the console and refresh the page see when our printable component will render first time it console this print table runs now i change the number and that calculate table function will change and it's read under print table component and it again console this print table runs which is working fine now when i toggle theme it again consoles this print table runs which means printable component gets read under even if we toggle the theme and that's the performance issue because when we change any state in this component this function will recalculate and even if our number is same it will return the same value with new instance so react things it's a new result and then it re-rendered the print table component now we have to stop this unwanted function recreation and that's why we use use callback hook and the good news is use callback is exact same as the use memo hook so there is a little difference in use callback and use memo hook so use memory returns the memoize value and use callback returns the memoize function simple as that so first of all i import use callback from react and add here use callback now it accepts two parameters like use memo and use effect first one is callback function and second one is dependencies array so in dependencies i write number and in callback i simply copy and paste this return statement now we can store this function in variable called calculate table and i remove this old function so here if we use use memo we get only this value in this variable but if we use use callback then we get this full function in this variable and if we want to run this function we have to write like this so whenever we change the number only then and then this function will run now save the changes and take a look so when we increase number it console this print table runs and now i click on toggle button it will not console this print table runs so we fix this issue with the help of use callback now we can pass value as parameter in this function for example i pass 2 and here i store that in value variable and you can use it in this function so i create a new variable new number equals to number plus value and instead of this number we passed new number so we get table of original number plus 2. it depends on you how you can use this parameter remember in use memo you can't do that now let's recap what we learned so use callback is used to return memoize function and improve the performance of our react application use callback syntax is same as use memo hook but use memory returns the memoized value and use callback returns the memoize function and in use callback we can pass value as parameter but in use memo we can do that simple as that i hope you understand use callback hook and difference between use callback and use memo [Music] so what is custom hook custom hooks are basically reusable functions in simple terms custom hooks are your own hooks that you create for your own use and you can use them multiple times in your project for example you have some logic in which you use one or multiple built-in react hooks and you need to use that logic multiple times in your project so instead of writing the same long logic in every place you create your own hook or function which is a custom hook and you use it just like we use other react built-in hooks simple as that let's create one of the most useful custom hook for fetching data from api i love this custom hook because i use it a lot in my projects so here i create one simple example in which we call api for random users details and display their names with id so first of all i create one state variable called responses and pass an empty array as its initial value after that i use use effect hook with empty array dependencies so it runs only when component gets rendered first time and in use effect i pass data from this api and convert it into json format and then set that data in set responses and after all that i display that data using map method now imagine you want to fetch data from api in 10 to 12 components so you have to write this code in all of those components which is not a good practice in react so we will create custom hook for fetching data so first of all i create one folder called custom hooks we will store all our custom hooks in that folder to organize our code which is a good practice for developers so in this folder we create a new file called use fetch.js always start your custom hook name with use keyword which is a common convention now i write rafce for functional boilerplate by using this es7 react extension so first of all i cut this state and use effect from this component and paste it into use patch and import use effect and used it from react library now we accept one parameter in this function called url and we use this url variable at the place of api so whenever we use use fetch we just have to pass api in this function and here we return this response's state variable and save it now back to our app component and we just try to use fetch and react auto import that from our custom hooks folder so in this use fetch function we can pass any api and we can store that array value in data variable and at last we change this responses with data variable now i remove use effect and used it from here we don't need them now save the changes and take a look we get our data so we successfully create our first and most useful custom hook you can see our code looks neat and clean so this is just one example now it's on you how to use your logic for different use cases so try to think and apply your logic and create custom hooks which will help you in your future projects so let's recap what we learned custom hooks are your logic which you created as reusable function and in that you can use multiple hooks and create something that will help you to skip repeated task in your project also you can simply use that custom hooks in your different projects so congratulation you completed all react hooks now you can apply these hooks in your projects and if you want to revise a specific hook you can save this video in your watch list so that's it for today see you in the next tutorial goodbye
Info
Channel: Code Bless You
Views: 77,370
Rating: undefined out of 5
Keywords: code bless you, react js tutorial, react tutorial, react hooks, usememo, react tutorial for beginners, useref, useeffect react hooks, usereducer, usecontext, usestate react, hooks in react js, hooks react, react hooks tutorial, usecallback, custom hooks react, uselayouteffect, all react hooks, usestate, react js, reactjs, reactjs tutorial, usecallback react hooks, react custom hooks, react js hooks, reactjs hooks, usecontext react hooks, react hooks explained, useEffect, react hook
Id: HnXPKtro4SM
Channel Id: undefined
Length: 59min 28sec (3568 seconds)
Published: Thu Jul 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.