React hooks, a starting guide

Mateo mojica
7 min readJun 4, 2022

--

Photo by Joe Dudeck on Unsplash

React is one of the most popular frameworks in the industry right now because it lets you build modular applications and reuse a lot of code. To expand this functionality the React group introduced a couple of years back functional components and hooks to be able to expand on this mantra of modularity. In this article, you will learn about the basics of hooks and how to use them.

Hooks have been around since React 16.8 and their purpose is to let you use Class component features (such as state and life-cycle methods) without writing a class. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and life-cycle, and they provide a powerful way to combine them.

Photo by Zyanya BMO on Unsplash

For class components, there are two barriers that attack the most important sides of development, people and machine. For people, classes can be a little difficult to understand due to all the overhead and concepts that they imply, on top of that you have the complexities that Javascript itself imposes on classes (like binding, prototyping, and the concept of this) and you have a very complicated way to write code. Another downside to class components is code readability, this can be affected by the limited functionality of the methods used for the life cycle, which makes developers bundle unrelated logic into the same method. The last problem is that any optimization that you might have for your code, like pre-packing components or minification, can be compromised by class components and can make hot reloading unreliable.

This is where hooks save the day, addressing these and more problems, by letting you use more of React’s features without classes. Hooks embrace functions, that for developers are much easier to grasp. Also, it is worth noting that hooks work alongside classes and any existing code, but are the standard moving forward on React development.

Hooks are here to stay and are the future of React functionality, they cover all the use cases that a class can have and more, and they make the code simpler to write and more readable, so in any circumstance, you should use hooks. However, if you are used to developing with classes and have a better understanding of the life-cycle methods there, especially the component did mount, you can still use class components to help with this task, since it can be difficult to do with hooks in an intuitive way. But it is highly recommended that you lay out the functionality with the class component to tune it how you want it to work and then try to replicate it with hooks to get a fully detailed knowledge of how to use hooks.

Photo by Max Duzij on Unsplash

Now let’s get into the inner workings of hooks, starting with the most basic one useState. This hook is very simple but it can have a lot of complexities and different ways to use it depending on what you need so let’s get started.

The useState hook is used, as its name implies, to manage the state of your component, this can be one variable or be split into several variables. It is not recommended to use an object as a whole complete state due to complexities in updating a specific part of that state and affecting other values that were not supposed to change. useState takes the initial value for the state as an argument and returns an array of two things, the first position is the actual state, so the value that it currently has, and the second position is the function that we use to change (or set) the value of the state. This state can be set asynchronously, meaning that every time you use the set function no matter how many times you call it inside a callback it will always update the state only once, if you want the change to be reflected immediately what you have to do is to pass a callback function as an argument for the set function, this callback will take the current state value as an argument and then you can manipulate the value to change the state, this change will reflect the change right away and when you call the set function several times it will update every time it is called.

useState hook code

Let’s move on to the next hook called useEffect. This hook is the one that allows us to replicate the behavior of life-cycle methods inside functional components, but it also extends that functionality and allows us to track individual or grouped variables (states, props, etc) by using the dependency array, this allows for isolation of functionality for the code improving its readability.

The useEffect hook takes two arguments, the first is the callback function that is going to get triggered when the hook is activated, and the second one is a dependencies array, this argument is optional and allows you to specify which variables are going to trigger the callback when they change. This dependency array is the one that allows us to mimic the component did mount (passing an empty array) and component updated methods for classes (not passing an array). It is worth noting that when you specify a variable inside the dependency array it will run at the mounting of the component and every time that variable changes, so for more precise functionality it is better to keep track if the component is already mounted with a state. You can also return a callback function to be executed when the use effect ran, this function is going to be executed first and then whatever else is inside the hook is going to run second.

useEffect code example

We already saw the most used and important hooks that will help, in most situations, to replicate the functionality that class components have. Now let’s dig into the more use-case-specific and obscure hooks that react presents.

Starting with the useMemo hook. This hook is used to cache the value of a dependency, so when you use it inside the application and the component re-renders without that value changing it will remember that value and use it, making your application faster, this is known as memoization.

useMemo code example

The useCallback hook is very similar to the useMemo hook but instead of caching values, it caches functions to run when the dependency changes instead of running on every re-render.

useCallback hook code example

Another common hook is the useRef. It allows us to get an HTML element without having to select it from the DOM, just by using it we create a pointer to that element that has the ref attached to it allowing us to manipulate it and its properties by just using that pointer.

The useContext hook will create a store, and anything that is inside it will be accessible in the entire application, similar to what Redux does with its store. This hook is a little more advanced to use because it requires some setup inside the application, like setting up the context and the providers for that context. If you want to know more about this hook feel free to go to the documentation.

The last hook we are going to talk about is the useReducer hook. This hook allows us to manage our state in a very controlled way (it is the same way as the state is managed in Redux), by using specific actions and controlling what those actions do to the state when they are dispatched, and if an action is not in the white list the reducer just leaves the state as it is. It introduces a little overhead because you have to define the reducer and the actions in order for it to work but it gives you a very safe way to manage your state.

useReducer hook code example

Many people use a combination of useContext and useReducer to replace Redux in their applications.

Since you are using functional components already, remember that they are functions, not classes, react lets you create your own hooks, which are also functions, to extract logic that you want to access or reuse in different parts of the application, this is possible because the whole paradigm of hooks is functions calling other functions. This functionality lets you modularize even further your code than you could before. You can read more about custom hooks in the documentation.

This was a fun trip through the world of React hooks, as we learned what they are, when and how they are used, and also about some of the basic hooks that come out of the box.

That is all I wanted to share with you about hooks but many other hooks are not covered here. If this article poked your interest in hooks, check the documentation for a deeper understanding of hooks.

I hope this article helped you to understand better react hooks and get you started on your React journey. If you liked it please give it a clap and check out my other articles.

References

https://www.youtube.com/watch?v=4Cf86qVEIJY

https://reactjs.org/docs/hooks-intro.html

https://www.youtube.com/watch?v=dpw9EHDh2bM

https://reactjs.org/docs/hooks-reference.html

--

--

Mateo mojica
Mateo mojica

Written by Mateo mojica

Electronic engineer and software developer

No responses yet