Skip to main content

Building custom Hooks

Introduction

Hooks are a new addition in React 16.8, which allow you to use state and other React features without writing a class. In this tutorial, we'll focus on building custom Hooks. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.

Why Custom Hooks?

Sometimes, we want to reuse some stateful logic between components. Traditionally, there were two popular solutions to this problem: higher-order components (HOCs) and render props. Custom Hooks let you do this, but without adding more components to your tree.

Custom Hooks are more of a convention than a feature. If a function's name starts with ”use” and it calls other Hooks, we say it is a custom Hook. The useSomething naming convention is how linter plugin is able to find bugs in the code using Hooks.

Building Our First Custom Hook

Let's say we have a simple function that allows us to toggle the visibility state of an element:

import { useState } from 'react';

function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggleValue = () => setValue(!value);

return [value, toggleValue];
}

Here, useToggle is our custom Hook. It takes an initial value for our state, and returns an array containing the current state value and a function to toggle that state value. We can now use this custom Hook in our components like so:

import React from 'react';
import useToggle from './useToggle';

function App() {
const [isVisible, toggleVisibility] = useToggle(false);

return (
<div className="App">
{isVisible && <p>Now you see me!</p>}
<button onClick={toggleVisibility}>
Toggle Visibility
</button>
</div>
);
}
export default App;

In the above code, we import our custom Hook useToggle and use it inside our App component to manage the visibility state of a paragraph element. We initially set the isVisible state to false, and every time we click our button, toggleVisibility is called, toggling the isVisible state and subsequently the visibility of the paragraph.

Rules of Hooks

While Hooks are a new concept, they also come with a new set of rules:

  • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  • Only call Hooks from React functions. Don’t call Hooks from regular JavaScript functions.

Following these rules will ensure consistency and predictability in your code.

Conclusion

Custom Hooks offer a great way to share logic between components, without altering the structure of your component tree. They provide a powerful way to encapsulate stateful logic, so it can be easily tested and reused across your applications. With the ability to leverage other Hooks, the possibilities for custom Hooks are almost limitless - so start experimenting, and see how they can improve your React applications!