DEV Community

Cover image for How to Create a Custom Hook in Your ReactJs Application
Hamzat Abdul-muizz
Hamzat Abdul-muizz

Posted on • Updated on

How to Create a Custom Hook in Your ReactJs Application

A hook in React is a JavaScript function that enables you to encapsulate reusable logic and stateful behavior within functional components. Hooks allow you to modularize code by extracting common functionality from components, promoting cleaner and more maintainable code. With hooks like useState, useEffect, and useContext, developers can efficiently manage component state, handle side effects, and share state across components.

In this article, we'll delve into the creation of a custom hook that enables you to implement a toggle functionality, which can be utilized across different parts of your React app. We'll explore best practices and offer solutions to potential errors you might encounter during the integration process. Familiarity with JavaScript and ReactJS is assumed for this tutorial. Please note that while we will use 'yarn' for package management, you can substitute 'npm' wherever applicable.

Final Preview

Setting Up Your React App

Before we dive into creating custom hooks, ensure you have a React app set up. If you haven't already, you can create a new React app using the following command:

yarn create vite
Enter fullscreen mode Exit fullscreen mode

Once your server is up and running, you should have a directory structure similar to this:

Server Up and Running

Creating a Custom Toggle Hook

1 . Inside your "src" folder, create a subfolder named "hooks" and add a new file named useToggle.jsx.

project-root/
  src/
    hooks/
Enter fullscreen mode Exit fullscreen mode

2 . Define Your Custom Hook:

import { useState } from "react";

const useToggle = (initialValue = false) => {
  const [state, setState] = useState(initialValue);

  const toggle = () => {
    setState(!state);
  };

  return { state, toggle };
};

export default useToggle;
Enter fullscreen mode Exit fullscreen mode

In the above code:

  • We import useState to handle the current state of the toggle.
  • The custom hook useToggle is created, which accepts an optional parameter initialValue. If not provided, the default value is false.
  • The toggle function is defined within the hook, toggling the state between true and false.
  • Importantly, remember that hooks return logic, not UI components.

Using the Custom Toggle Hook

To utilize the custom hook in your components, follow these steps:

1 . Import the useToggle hook:

import useToggle from '../hooks/useToggle';
Enter fullscreen mode Exit fullscreen mode

2 . Get the return values from the hook using destructuring:

const { state, toggle } = useToggle();
Enter fullscreen mode Exit fullscreen mode

3 . Implement the toggle functionality in your app's UI:

<div>
   <button onClick={toggle}>
       {state ? "Hide" : "Show"}
   </button>
   {state && <h1>Hidden Text</h1>}
</div>
Enter fullscreen mode Exit fullscreen mode

Using the Custom Hook Across Components

If you want to use the custom hook across multiple sections of the same component, you can avoid state conflicts by renaming the variables. Here's how:

const { state: showData, toggle: toggleData } = useToggle();
Enter fullscreen mode Exit fullscreen mode

In this tutorial, you've learned how to create a custom hook that encapsulates the toggle functionality within your React app. By extracting common logic into reusable hooks, you can enhance code maintainability and promote a more organized project structure. This approach empowers you to efficiently manage complex behaviors and state in functional components, making your codebase cleaner and more modular. Happy hooking!

Remember that practice is key to mastering custom hooks and React's vast ecosystem. As you become more comfortable with hooks, you can explore other hooks and share your experiences with the community.

Feel free to explore more complex custom hooks and experiment with various use cases to further solidify your understanding of this powerful feature in React development.

Link to the code here


Top comments (2)

Collapse
 
dideoluwa_folorunso_377c8 profile image
Dideoluwa Folorunso

Excellent writer up šŸ‘

Collapse
 
canhamzacode profile image
Hamzat Abdul-muizz

I am glad you like it šŸ˜Š