Why I decided to use React hooks for all projects
Hooks are introduced from react 16.8.0. In very simple terms it let you use state, life cycle methods without writing a class. Before I start, it is advisable and recommended to watch the following video.
So, let us first discuss the need for hooks and practical problems it intended to solve.
Problems
- Sometimes we heard people talking about react doesn’t let you separate the concerns. We usually have data fetching, form validations, animations etc. And if you try this out only with components, what you end up with is nothing but huge components, duplicate logic. For example, you have to write the code that fetches or send the data to your API service on every single page. Hooks allow you to remove this overhead.
- Earlier you need to separate the logic for your website on the basis of life cycle method. For example, you may subscribe to some end point in componentDidMount method and then you definitely have to unsubscribe in componentWIllUnmount. Similarly, you might have to update the same in other life cycle method. But sharp readers have easily pointed out that we essentially performing actions on the same object, then why we need a separate method for each of that. This is the point where hooks jump in and will save you. Hooks allow you to separate the code on the basis of action it is performing and not the life cycle. Following the example above, now you can subscribe, unsubscribe and update the same object form single useEffect hook. I will give an example in the latter part.
- This is not a completely new concept. Earlier we have to use Higher Order Component(HOC) or Mixins to achieve the same functionalities as hooks. But this requires much more code and still not allow us to share the code to the extent of hooks. It also makes your code unreadable and further harder and harder to debug.
- For many people ‘this’ keyword is really annoying, we need to bind every function call with ‘this’, append ‘this.’ before using any state/props variable. But with hooks, this problem goes away as we will discuss next with simple examples.
We definitely need a solution to all of these problems discussed. And this is the reason why hooks are introduced. Next we will discuss a very simple example of hooks and at last, I will provide an example for how to build your own hooks. So, first, we will talk about some of the hooks react comes bundled with.
Built-in hooks
useState — This hook as the name indicates used to initialize the state and later on to set the state. Its use is as shown
[loggedin, setloggedin]=useState(false);
This hook will return two array elements. First is simple state variable and other is the function and now we can use that function to change the state of a loggedin variable. In our example,
setloggedin(true);
This line is equivalent to this.setState({}) that we all are familiar with. You can anywhere in that function directly use the state variable loggedin.
useEffect — Think about this in a better way. Let’s say you already have functional components and suddenly you need to add life cycle method to it. One solution is to convert it to class-based components, copy all your code and now you can very well add all the life cycle method. But relax you don’t need to do any of that. useEffect hook comes to your rescue. I will show you how this hook can be used as different life cycle method one by one.
useEffect as componentDidMount — Let’s say you want to add the dynamic title to your particular page. Definitely, you need to add this in the componentDidMount method. Following example show how you can achieve the same with useEffect.
useEffect(() => {
console.log("useEffect hook called");
document.title = 'Learn hooks';
}, []);
useEffect takes two arguments, one is obviously the function we want to execute. But this function will be executed after page renders. So, whenever the state or props changes this function will be executed again. And you never want this. So, the second argument it takes as an input is the dependencies list. Now function will be executed only if one of these parameters changes. And there you go, just pass the empty list and tell it that it does not depend on anything, thus it will be executed only once.
useEffect as componetDidUpdate — This method is invoked immediately after updating occurs and not called for the initial render. So, if you have an application where you need to fetch the data from the API whenever the user changes the search tag or string then here is the way out using useEffect as componentDidUpdate
useEffect(() => {
console.log("component updated");
fetchData(props.searchTags)
}, [props.searchTags]);
We are passing an array with props.searchTags instead of just empty array as earlier. Now code inside the function we have passed as the first argument will run whenever searchTags props will change and thus we have successfully accomplished the componentDidUpdate method with useEffect that too without any overhead of writing if else condition to check whether that props are changed or not.
useEffect as componentWillUnmount — This method is invoked just before the component is unmounted and destroyed from the DoM. To implement this method with a given hook, I need to unveil one more feature of this hook that function we are passing as the first argument can also return the function that will run right before the useEffect will run next time. and will also run the last time. So, after knowing this awesome thing one can easily guess that we can very well implement unmounting by just returning the function from componentDidMount implementation.
useEffect(() => {
console.log("useEffect hook called");
return()=>{
console.log('component destroyed')
}
}, [])
As we are passing empty array list it will only run when component mount and as we are returning the function so that function will run again when the component is destroyed.
At this point, it is clear that how hooks are going to change the life of react developers. And finally, let’s see a simple example of how to implement our own hook that allows sharing of the logic.
Custom Hooks
And to use this hook we need to pass the
const [isLoading, data]=useApi('/allUser', []);
isLoading and data are the variables that useApi hook is using, we are passing the URL and dependency list as an argument to the hook. Now you can use this hook on any page and for that matter any application where you need to fetch the data from the API. This is how hooks allow you to share the logic.
Wrap Up
After reading this article I hope that you have a concrete idea of working with hooks. I advise you to try it on your own by converting any existing react application from class-based to functions. That will help you a lot.
Please let me know in comments, if something isn’t clear to you, and I’d be happy to chat about your concerns. Thank you for reading!
If you would like to get notified of my articles and updates, Follow me on Twitter and Medium.