From the course: Building Production-Ready React Apps: Setup to Deployment with Firebase

Introduction to Hooks API Reference

- [Instructor] Hooks are new additions to the React library since version 16.8. They're allowed to add logic to a functional component without having to write a class. So what is a Hook exactly? According to the React documentation, a Hook is a special function that lets you hook into React features. For example, first you have useState which is a Hook that lets you add state and logic to a function component like this example right here. And there is useEffect, another Hook to apply side effects. So why you should use the Hooks? Before the introduction of the Hooks you had to write a class to use logic. Now with the Hooks, you can write stateful components and you can also manage the state and logic inside a functional component without having to write a class. With the help of the Hooks you can write the same logic separately and reuse the same logic. It also helps to simplify how to make the code more composable and reusable. Plus the code is easier to maintain and to test. Let's look at one Hook example online with the equivalent of an example of a class first. So right below you have the Equivalent Class Example. So we're going to start with an example of a counter. We start with the state with a count of zero and then each time that the user clicks on a button the value of this state is going to increment by one. With this state's count, and we're going to apply the value of this state count plus one to increment the value. So now let's look at the same example with the Hook. First we import useState from the React library. Then we're going to add useState inside the function components to create a stateful component. And here as well, the initial value is zero. It's going to return an array, so the state variable and the function that's going to allow to update the states. And this is what we do right here with this button. So each time that the user clicks on a button it's going to increment the value by one with setCount that takes one parameter, and that's going to be count plus one to increment the value of the state. So what are the benefits of using the Hooks? The Hooks allow to do the same thing as a class but without having to write a class with much less implementation and code. The React Hooks make the code more simple, more flexible, and more composable also. And it is good to know that functional components with the Hooks have become the most common and current practice compared to the class. In the upcoming videos, we're going to continue to build our file stack React application to create functional and stateful components. First, we learn about the Hooks useStates and useEffect to change the state, and then to apply sideEffect when there is a change in the state, and other Hooks like useMemo and useRegister. So let's see how to hook into React with the Hooks.

Contents