React Hooks and How to Create a Custom Hook

Johnson Liu
3 min readMay 31, 2021

When you first start out using React, an open-source front-end JavaScript library for building user interfaces or UI components, you are immediately introduced to React Hooks. Why? Because you will use it throughout your application. One key advantage with using Hooks, is that you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing or moving your component hierarchy. This makes it easy to share Hooks among many components.

Some of the most common React Hooks are useState and useEffect. In Javascript class components, we are used to “this”, but here with Hooks, we replaced it with useState. Below is a simple counter for a button on the page. We pass in an argument and initialize the counter at zero and incremented by one every time the button is clicked.

We pretty much name the useState anything, as long as we have a “name” and a “setName” to help us see the change in value. useState returns a pair of values, the current state its and the function that updates it. Below is another example of how we can implement useState and have it as a toggle to show us if an item is in stock or out. We first pass in the argument of true to show that our item is in stock. One click, the state would change to the other condition, giving us a toggle showing if an item is in stock.

The useEffect hook tells React that your component needs to perform an action after rendering. React will remember the function you passed and call it later after performing updates on the DOM (or virtual DOM). Often times useEffect is used to fetch data from a link or an API. Like the example below, we use the useEffect Hook to implement a fetch request. After rendering, you can then take this data to use it to your liking.

Creating a custom hook is not as hard a you would think. If you ever run in to the situation where you want to use a custom hook in your application, you just need to create a separate component.

Once you have created that separate component, you can set your functions and your actions within that component. Then finally, in the component that you want to use the custom hook, import it like you would with other components. Once it is imported, you can call on the custom hook.

If you want to learn more about React Hooks, the React documentation linked is a great resource. There are also videos that show you have to step by step how to implement a custom hook.

--

--