ALL React Hooks Explained in 12 Minutes

136.71k views2255 WordsCopy TextShare
Code Bootcamp
My React course: https://reactbootcamp.dev Chapters 0:00 - Intro 0:32 - Map of Hooks 1:02 - useStat...
Video Transcript:
so you've decided to make a react app which means you're going to build it with the help of react hooks the only problem is there are a lot of different hooks so which ones should you use let's answer that question by looking at all the hooks and see what each one does all the best ways to use each hook and how often you'll need to use them a lot rarely or almost never here's a neat trick to make learning hooks much easier because there's actually a convenient pattern to how all the hooks fit together I've
created a complete map of react hooks to show you all eight major categories that each one falls into starting with State Management hooks to work with react State effect hooks to perform side effects ref hooks to reference JavaScript values or Dom elements performance hooks to improve app performance with memoization context hooks to read from react context transition hooks to use transitions for better user experiences some random Hooks and some powerful new hooks introduced in react 19 and we'll begin with the hook you'll likely use the most now UST state is probably the bread and butter
of any react developer Because unless you're using a framework you'll use it a lot a big reason why react exists is to help us manage State and render components when State changes Ed state is best for client components that need their own simple specific State and there are so many cases where we need to manage State and react Ed state is probably the most versatile hook we'll cover to use it you can give it an initial value which can virtually be any JavaScript value and that will then be stored in your state variable that's returned
when you call Ed State it's returned in an array which can be destructured as two separate variables where the first one is the state variable and the second is a function to update that variable UST state is great for capturing user input in form Fields like inputs text areas and selects it can be used to show or hide components like modals tool tips or dropdowns when you give it a Boolean State value you can also use a Boolean State variable as well to conditionally apply classes and styles and working with number values like in a
shopping cart or counter is another perfect use case for used State use reducer is another state hook that's useful for performing more complex State Management than used State you won't need to use it very often but it's worth adding if you have a lot of related State use reducer uses a reducer function to update state which can radic simplify your code because all the State updates can be done in a single function us reducer accepts both a reducer function and a starting State value and like used state it returns an array which includes the state
variable and a new function called dispatch when dispatch is called it runs the reducer function and sends data to it called an action the benefit of the action data is to conditionally set State based off of what action came in US reducer works well for simp simplifying components with multiple related State values like multiple inputs within a form it's also good for components where the state depends on other values like in this game based example this makes use reducer a great choice for apps with lots of user interactions a state hook you might not have
heard of however is use sync external store this is one of those hooks you're likely not going to use at all it's primarily used to add non-react State Stores into react components which means you're not going to need it unless you want to make your own State Management library from scratch after State hooks we have effect hooks which let us perform side effects but what is a side effect it's a way to reach out side react and synchronize with an external system a good basic example of performing a side effect is to set the title
using the document API to do that you first give use effect a function to run and by default it'll run after each render to change that behavior you can give it a dependencies array when any value in this array changes the effect function will run and when the button is clicked count will be updated in state which will cause the effect function to run and update the title let's take a look at two types of side effects event based side effects which run when some event takes place like a button click and render based side
effects which is a side effect which runs after render such as fetching data and it may surprise you but use effect really shouldn't be used for either type instead of Performing side effects when an event happens and use effect make your code simpler by doing it directly in an event handler and instead of fetching data when your component mounts and putting it in state use a more sophisticated tool to fetch data like react query or data fetching patterns that come with Frameworks like nextjs when should you use effect then you won't need to use it
often but mainly when you need to sync your react code with a browser API like in this example where we're synchronizing the react state with the browser media API using a ref and either playing it or pausing it and in fact there's a more specialized version of use Effect called use layout effect while use effect runs after react Paints the UI use layout effect runs just before react Paints the UI while use effect is asynchronous this Hook is primarily for synchronous operations that you want to do right before displaying the UI content like setting State
and this particular use case means this Hook is going to be used even l L than use effect use layout effect is good to use for example when you want to get some initial state from a browser API like this one where we're measuring the height of a tool tip with get bounding client wreck and then setting it in state before the browser repaints and it's visible to the user use insertion effect is an even more Niche effect hook you've probably never heard of because it's made exclusively for CSS and JS Library makers libraries like
styled components Orem motion this hook runs before use effect and use layout effect run and it does so in order to make sure any CSS styles are inserted if other effect hooks need to read from the layout like effects refs are a way to step outside of react the used ref Hook is kind of like used state it lets us remember data but without triggering a render like UST State refs can be given any data value but it's simpler because it returns only one value which is whatever you passed it and to access the underlying
value you can use the current property another important difference between refs and state is that refs are mutable while state is immutable this means the current property can be modified directly using the equals operator this is really useful in this timer example where we're storing the interval ID in a ref to clear the interval when we want to using the stop timer function Dom elements can also be stored in refs you can do this by connecting a created ref to the ref prop of an element once you do that use the current property to access
the underlying Dom element use imperative handle as a type of ref hook but rarely used it's only necessary to use when you need to forward a ref which means you need to pair it with the forward ref function and only if you also need to expose a method to the parent component that pass the ref let's say you have a parent component that wants to focus an input within a child component to do that you need to First forward the ref to the child with with the forward ref function which won't be required in react
19 and to expose the focus method to the parent ref you use use imperative handle to put that method on the ref use memo is one of two hooks made to improve your app's performance it uses something called memoization to improve performance by caching previous results use memo will recompute the cache value only when one of its dependencies has changed and this makes it good for performing expensive computations use memo looks similar to use effect but it's not for side effects and it must return a value a heavy computation that use memo might do is
calculate the sum of numbers in an array it only reruns this function when the numbers array changes and it puts the computed result in the sum variable like use memo Ed callback memorizes what's passed to it but use callback is different it's for functions specifically callback functions that are passed down to filed components this improves performance by preventing callback functions from being recreated on each render in this example we're passing the increment function as a prop to the button component since that function updates State it'll cause a rerender whenever it's run so to prevent the
increment function from being recreated every time the component reenders we wrap the increment function and use callback there's one context hook called use context and it's really pretty simple it can read context values which means if a component is wrapped in a context provider you can use this hook to read the value passed down on context use context Works in any component that's nested inside a provider no matter how deep it is to read the context value you just need to pass the created context to Ed context and that's it in react All State updates
are considered to be urgent use transition as a transition hook that allows us to specify that certain State updates are not urgent this is helpful for State updates that involve heavy computations which can lead to a bad user experience if they're executed immediately we can make our app more responsive by wrapping these State updates in a transition a great use case for Ed transition is filtering a list based on user input typing into the input might cause the UI to freeze or be sluggish because the app is trying to render the list after each keystroke
we can mark the filter State update as non- urgent with the start transition function from use transition use transition also gives us an is pending Boolean value to tell us when the transition is pending allowing us to show a loading state to the user until the state update finishes use deferred value is another transition hook that lets you defer or pause an update to keep your app responsive it's very similar to used transition but we use it to tell react to schedule an update at an optimal time for us instead of us doing it ourselves
to use it all you need to do is pass the value you want to defer to use deferred value just like the used transition example used deferred value is best for things like filtering lists this leads to the same improved user experience as used transition but without you having to manually start the transition or use any pending State the only reason to use a random hook like use debug value is if you regularly use react Dev tools if not the you probably won't ever use it but if you do and you're using custom hooks use
debug value lets you label your custom hooks with whatever string value you pass to them that way you can find your custom hooks easier in the react Dev tools extension use ID is another random hook that does exactly what it says it creates a unique ID when it's called and it doesn't require any arguments but I know what you're thinking and no you can't use it to create keys for your list items it's made for creating Dynamic IDs to be shared between form inputs and their labels use ID is useful when form inputs can be
reused multiple times in a single page in this form component we're using the email input component twice so to make sure they each have unique IDs that don't conflict with each other we use use ID to make unique ID to keep them separate there's so much more to learn about react hooks to really Master them and to help you do that plus every other react topic I've created a complete boot camp with tons of interactive challenges fun fun videos and super helpful cheat sheets with all the code and examples we covered here you can find
all that and more at react Boot camp. and as for the react 19 hooks here I have a complete video that covers them all in depth what they do and how to start using them today just click here to watch that now thanks for watching and I'll see you in the next video
Copyright © 2024. Made with ♥ in London by YTScribe.com