Skip to main content

Creating Your First Custom Hook: `useToggle` (Part 1) - A Simple and Practical Example #82

📖 Introduction

Following our exploration of The Power of Custom Hooks, this article provides a practical, hands-on example of creating your first custom hook: useToggle. This is a classic and incredibly useful hook that you will find yourself reaching for again and again in your projects.


📚 Prerequisites

Before we begin, please ensure you have a solid grasp of the following concepts:

  • React Hooks, especially useState and useCallback.
  • Functional components.
  • Basic JavaScript arrow functions.

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • The Problem: Understanding the repetitive state logic that useToggle solves.
  • Core Implementation: How to build the useToggle hook from scratch.
  • Practical Application: How to use the useToggle hook in a component to show and hide a UI element.

🧠 Section 1: The Core Concepts of useToggle

How many times have you written this piece of code?

const [isOpen, setIsOpen] = useState(false);

const toggleOpen = () => {
setIsOpen(!isOpen);
};

This pattern is extremely common. You use it for modals, dropdowns, accordions, and any other UI element that needs to be shown or hidden. While it's not a lot of code, it is repetitive. This is a perfect opportunity to create a custom hook to encapsulate this logic.

The useToggle hook will:

  1. Hold a boolean state value.
  2. Provide a function to toggle that value.

💻 Section 2: Deep Dive - Implementation and Walkthrough

Let's build the useToggle hook.

2.1 - The useToggle Hook

Create a new file called useToggle.js:

// useToggle.js
import { useState, useCallback } from 'react';

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

const toggle = useCallback(() => {
setValue(v => !v);
}, []);

return [value, toggle];
}

export default useToggle;

Step-by-Step Code Breakdown:

  1. import { useState, useCallback } from 'react';: We import the necessary hooks from React.
  2. function useToggle(initialValue = false) { ... }: We define our custom hook and give it an optional initialValue that defaults to false.
  3. const [value, setValue] = useState(initialValue);: We use the useState hook to manage the boolean value.
  4. const toggle = useCallback(() => { ... }, []);: We create a toggle function that will set the value to the opposite of its current value. We wrap it in useCallback to ensure the function is not recreated on every render, which is a performance optimization.
  5. return [value, toggle];: We return the current value and the toggle function in an array, just like the useState hook.

🛠️ Section 3: Project-Based Example: A Show/Hide Component

Now, let's use our new useToggle hook in a component.

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

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

return (
<div>
<button onClick={toggleVisibility}>
{isVisible ? 'Hide' : 'Show'}
</button>
{isVisible && (
<div>
<p>This content is now visible!</p>
</div>
)}
</div>
);
}

export default ShowHideComponent;

Code Breakdown:

  1. import useToggle from './useToggle';: We import our custom hook.
  2. const [isVisible, toggleVisibility] = useToggle(false);: We call our useToggle hook and destructure the returned values into isVisible and toggleVisibility.
  3. <button onClick={toggleVisibility}>: We use the toggleVisibility function to toggle the isVisible state when the button is clicked.
  4. {isVisible && ...}: We use the isVisible state to conditionally render the content.

💡 Conclusion & Key Takeaways

Congratulations! You've created your first custom hook. You've seen how a small amount of code can be extracted into a reusable function that makes your components cleaner and more declarative.

Let's summarize the key takeaways:

  • Custom hooks are a powerful way to extract and reuse stateful logic.
  • The useToggle hook is a simple but incredibly useful hook for managing boolean state.
  • By creating custom hooks, you can make your code more readable, maintainable, and reusable.

Challenge Yourself: To solidify your understanding, try to create a component that uses the useToggle hook to show and hide a modal window.


➡️ Next Steps

You now have a solid understanding of how to create a simple custom hook. In the next article, "Creating Your First Custom Hook: useToggle (Part 2)", we will explore how to add more features to our useToggle hook to make it even more powerful.

Thank you for your dedication. Stay curious, and happy coding!


glossary

  • useToggle: A custom hook for managing boolean state.
  • useCallback: A React hook that returns a memoized callback function.
  • Declarative: A style of programming where you describe what you want to do, rather than how to do it.

Further Reading