5 REACT CUSTOM HOOKS You Should Start Using (Explained)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Thanks for sharing

👍︎︎ 2 👤︎︎ u/JoyShaheb_ 📅︎︎ Feb 07 2021 🗫︎ replies
Captions
are you repeating yourself by building the same features again and again in your functional components then in this video we're gonna cover the five custom hooks i use every single day in most of my react application and that you should start using those five react hooks will boost your productivity speed up your development process and save you a lot of time so you can work on more valuable features for your project or application so let's dive in what's up guys this is greg with alta class helping you learn the right skills to learn your dream job as a software engineer and if you are new here make sure to like the video subscribe to our class and consider becoming a pro member at theclass.io to learn everything you need to master react and become a successful react developer and all the links to everything i mentioned in this video can be found in the description box below so make sure to check this out so now let's jump into it react hooks have been introduced to the library with version 16.8 it allows you to use states and other react features in your functional component so that you don't even need to write classes anymore in reality hooks are much more than that oox lets us organize the logic inside the components into reusable isolated units there are a natural fit for the react component model and the new way to build your applications hooks can cover all use cases for classes while providing more flexibility in extracting testing and releasing code throughout your application building your own custom react hooks you can easily share features across all components of your applications and even across different application so you don't repeat yourself and get more productive of building react applications right now we are going to take a look at my top five custom hooks recreate them from scratch together so you really understand how they work and exactly how you can use them to boost your productivity and speed up your development process so let's jump right into building our first custom rear cook how many times have you built a react application that needs to fetch data from an external source before rendering it to the users fetching data is something i'm doing every single time i'm building a react application i even make several fetching calls inside a single application and whatever the way you choose to fetch your data either with axios the fetch api or anything else you are always writing the same piece of code again and again across your react components and across your application as well so let's see how we can build a simple yet useful custom hook we can call whenever we need to fetch data inside our application this way we will be able to reuse the logic inside that react hook in any functional component to fetch data with just one line of code okay so let's call our custom hook use fetch these books accept two arguments the url we need to query to fetch the data and an object representing the option we want to apply to the request fetching data is a side effect so we should use the react use effect hook to perform our query in this example we are going to use the fetch api to make our request so we are going to pass the url and the options and once the promise is resolved we retrieve the data by parsing the response buddy for that we use the json method then we just need to store it in a react state variable okay but we should also catch and handle network errors in case something goes wrong with our request so we're going to use another state variable to start the error so we could return it from our orc and be able to tell if an error has occurred i use fetch hook will return an object containing the data fetched from the url or the error if anything won't happen finally it's generally a good practice to indicate to your users the status of an asynchronous request such as displaying a loading indicator before rendering the results so let's add a first state variable to our custom hook to track our request status we set the slotting variable to true right before launching our request and we set it back to false when it's done we can now return this variable with the others to use it in our components to render a loading spinner while the request is running so that our user know that we are getting the data they ask for one more thing before we see how to use our new custom hook we need to check if the component using our hook is still mounted to update our state variable otherwise we are introducing memory leaks in our application to do that we can simply create a variable to check if our component is still mounted and use the cleanup function to update this variable when the component unmounts and inside the promise methods we can first check if the component is mounted before updating our state all right now let's see how easy it is to fetch data with our user echo we just need to pass the url of the resource we want to retrieve from there we get an object that we can use to render our application let's move into our second custom hook use event listener this hook is responsible for setting up and cleaning up an event lister inside our components this way we don't need to repeat ourselves every time we need to add event listeners to our application it accepts our argument the name of the events we want to listen for the function to run whenever an event of the specified type occurs the target under which to listen for the event and finally a set of options for the event listener as with the previous work we'll use the react use effect hook to add an event listener but first we need to make sure that the target supports the add event listener methods otherwise we do nothing then we can add the actual event listener and remove it inside the cleanup function actually we're going to also use a reference object to store and persist the listener function across renders we will update this reference only if the listener function changes and use this reference inside our event listener methods we don't need to return anything from this hook as we are just listening for events and running the antler function passing as an argument it is not easy to add an event listener to our components such as in the following components to detect clicks outside a dom element here we are closing the dialog component if the user clicks outside of it for our third custom hook we will leverage the local storage of a browser to persist our component state across sessions for this one we need the name of the key to retrieve or update in local storage and an initial value that's it and we are going to return an arrow like the one you get with the react usted hook so this arrow will contain a stateful value and a function to update it while purchasing it in local storage so let's dive in first let's create the react state variable we will sync with local storage here we are using lazy initialization to read local storage parse the value if any has been found or returned the initial value passing as the second argument to our work in case something goes wrong while reading in local storage we just log an error and return the initial value finally we need to create the update function to return that is going to store any state updates in local storage rather than using the default one returned by the usted hook this function updates both the react state and the corresponding key value in local storage note that we can also support functional updates like the regular used hook and finally we return the state value and our custom update function now we are good to go and we can use the use local storage hook to purchase any data in our components in local storage in the following example we use it to store the application settings of the connected user okay let's move on to our fourth react look use media query this look will help us to test and monitor media queries programmatically inside of functional components this is very useful for example when you need to render a different ui depending on the device type or specific characteristics so our hook is accepting three arguments which are first the array of string corresponding to the media queries then an array of values matching those media queries in the same order as the previous array and finally a default value if no major query matches the first thing we do inside this hook is building a major curry list for each match media query we're going to use this array to get the corresponding value by matching the media queries and to do that we are creating a callback function wrapped inside the use callback hook we retrieve the value of the first media query in our list that matches or return the default value if none of them match then we create a react state to store the match value and initialize it using our function define above finally we add an event lister inside the usefx hook to listen to each major queries changes and we run the update function when changes occur here we don't forget to clean up all those event listener and return the state value from our hook a simple example i've used recently is to add a media career to check if the device allows the user to hover over elements this way i could add specific opacity styles if the user can over or apply basic styles otherwise okay guys one more hook to go this one is my favorite it allows me to easily and quickly apply the dark mod feature to any of my react applications let's see how to build such a hook these hooks aim to enable and disable the dark mode and demand and store the current state in local storage for that we are going to use two of the hooks we just built use media query and use local storage with used media query we can check the user's browser preference for dac mode then with the used local storage we can initialize store and purchase the current state dark or light mode in local storage finally the final piece of this hook is to fire a side effect to add or remove the dark class to the document body element this way we could simply add dark style to our application and if you are looking for an easy way to do it once again have a look at teluwin css which supports dark mode coupled with this hook tailwind css becomes the easiest and fastest way of implementing dark mode in any react application all right that's it guys thank you so much for watching i really hope that this video was useful for you make sure to check the description below for the link to the github repository to get the source code of all the hooks we just built together please share this video with your friends hit the like button and please don't forget to subscribe and check out class.io if you want to go further and master react i'm building the only course you will need to become a react developer and get that dream job thank you and see you [Music] been a soon too nice to y'all now i gotta up price so y'all snake eyes with dice for y'all shoulders on ice for y'all
Info
Channel: AlterClass
Views: 9,223
Rating: undefined out of 5
Keywords: reactjs, best react framework, best react framework 2021, best react framework 2020, best framework for react js, create react app, jamstack, reactjs tutorial, react js for beginners, react js, javascript, javascript tutorial for beginners, javascript tutorial, reactjs tutorial 2020, reactjs tutorial 2021, react and firebase, netlify tutorial, web development, web development 2021, programming, react hooks explained, react hooks tutorial, react hooks project
Id: eeRLmYL7S9I
Channel Id: undefined
Length: 12min 45sec (765 seconds)
Published: Mon Feb 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.