How to Write a Custom React Hook
By: Caelin Sutch
Tags: Programming, Software Development, JavaScript, Web Development, React

How to Write a Custom React Hook

A lesson on how to extract component logic into reusable hooks.

React hooks, released in React v16.8, have changed the way developers write code. By default, React gives us access to a set of powerful base hooks, like useState , useEffect , useReducer , and others, but we can also build our own custom hooks to abstract complex state logic.

Photo by v2osk on Unsplash

Wait, what are custom hooks?

When writing React applications, there’s bound to be instances where you find yourself using the same repetitive or redundant state logic across multiple components. With custom hooks, we can extract this logic into a function to make our code cleaner and more reusable.

Custom hooks are simply functions that encompass other hooks and contain a common stateful logic that can be reused in multiple components. These functions are prefixed with the word use . Custom hooks mean less keystrokes and DRYer code.

Before you write your own custom hook, keep in mind that the open source community has published thousands of hooks, so there’s a very high probability someone has written the logic you need and published it online.

However, that is of no concern to us, this article is going to be focused on how to write custom hooks, not whether or not you should write them. Let’s dive right into our first example.

useLocalStorageState

Lets take a look at this Counter component that stores its current count value in local storage:

Here, we’re using useState and useEffect to sync up local state to local storage. Now what if we want to duplicate this logic across multiple components? Instead of copying and pasting code, we’ll create a new custom hook to handle this logic.

useLocalStorageState takes in two parameters, the key and the default value. On first initialization, we get the count from local storage if it exists and set it to state, otherwise we use the default value. We then use the useEffect hook to keep our local storage synced with local state, and return our state and setState functions as an array. Notice how we stringify and parse the values from localStorage using JSON.stringify and JSON.parse meaning we can also store objects with this hook as well!

Now we can reuse this useLocalStorageState hook across any component we want!

useArray

Note that we don’t always have to return an array from a custom hook. In this example, we’ll be building a custom useArray hook that allows us to manage array states easier.

This hook is pretty intuitive. We return an object with a bunch of modifiers for our array state that allow us to easily manipulate the array. We take in an initial array as the hook argument, then provide add , clear , removeById , and removeIndex as additional functions besides the usual value and setValue operations.

Lets see how we would implement this hook in a component:

See how we’ve drastically reduced the amount of extraneous logic we would need in this component by using a custom hook? Pretty incredible.

Do we have to start our custom hooks with use ?

Technically no, but really yes. As per the React docs: “Please do. This convention is very important. Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it.”

Custom hooks don’t share state

Each instance of a custom hook has its own state, so unfortunately you can’t share state by default with a custom hook. However, if you pair up a custom hook with a global state library like Redux or Recoil, you can build custom hooks that interact with global state!

Conclusion

React custom hooks are incredibly powerful for writing cleaner, more maintainable, and DRYer code. We looked at a couple great examples of custom hooks, usLocalStorageState and useArray and how we can use them to reduce code complexity and increase reusability. Got some great custom React hooks you’ve used or made? I’d love to see them, feel free to comment below!

Keep in Touch

There’s a lot of content out there and I appreciate you reading mine. I’m an undergraduate student at UC Berkeley in the MET program and a young entrepreneur. I write about software development, startups, and failure (something I’m quite adept at). You can signup for my newsletter here or check out what I’m working on at my website.

Feel free to reach out and connect with me on Linkedin or Twitter, I love hearing from people who read my articles :)