Create your own Custom Hook in ReactJS🔥🔥

Create your own Custom Hook in ReactJS🔥🔥

·

5 min read

In this blog, we will be seeing everything about Custom Hook in ReactJs.


What are Custom Hooks in React?

Custom hooks are a powerful feature in React that allows you to extract and reuse stateful logic from functional components. They enable you to create modular and shareable pieces of logic, making your React code more organized, readable, and maintainable.


When to use or make custom hook in reactjs?

Custom hooks in React are beneficial when you find yourself duplicating or sharing stateful logic across multiple components. Here are some scenarios where using or creating custom hooks makes sense:

  1. Reuse of Logic:

    • Scenario: You have a piece of logic, such as state management or side effects, that is used in multiple components.

    • Use of Custom Hook: Extract this logic into a custom hook, making it reusable across different components without duplicating code.

  2. Separation of Concerns:

    • Scenario: A component is becoming complex due to a mix of stateful logic, side effects, and other functionalities.

    • Use of Custom Hook: Create custom hooks to encapsulate specific concerns, making your components more focused, readable, and maintainable.

  3. Complex State Logic:

    • Scenario: You have complex state logic that involves multiple state variables and their interactions.

    • Use of Custom Hook: Abstract away this complexity into a custom hook, providing a cleaner interface for components to interact with the state.

  4. Composition of Hooks:

    • Scenario: You need to combine multiple built-in hooks to achieve a specific behavior in different components.

    • Use of Custom Hook: Create a custom hook that internally uses other hooks, allowing you to compose and reuse this combination of functionality.

  5. Cross-Cutting Concerns:

    • Scenario: You have cross-cutting concerns like authentication, logging, or analytics that need to be applied across different parts of your application.

    • Use of Custom Hook: Implement these cross-cutting concerns in custom hooks, making it easy to manage and update these functionalities consistently.

  6. Testing Separation:

    • Scenario: You want to improve the testability of your components by separating the logic from the rendering.

    • Use of Custom Hook: Move complex logic into a custom hook, making it easier to test the logic independently of the component's rendering.

  7. Consistent Code Patterns:

    • Scenario: You want to enforce consistent patterns and practices across your application.

    • Use of Custom Hook: Create custom hooks that encapsulate common patterns, ensuring that developers follow the same conventions throughout the codebase.


Key points about Custom Hooks

  1. Reusability and Code Organization:

    • Custom hooks promote reusability by allowing you to extract and reuse stateful logic across multiple components.

    • They help in organizing your code by separating concerns and keeping components focused on their specific responsibilities.

  2. Encapsulation of Logic:

    • Custom hooks enable the encapsulation of complex logic, such as state management, side effects, or API calls, into modular functions.

    • This encapsulation makes your codebase cleaner and more maintainable, as each custom hook handles a specific piece of functionality.

  3. Hook Composition:

    • Custom hooks can internally use other hooks, allowing you to compose and combine multiple hooks to create sophisticated logic without duplicating code.

    • This promotes a modular and composable approach to building complex features in React applications.

  4. Improved Testing:

    • Custom hooks make testing easier by providing a clear separation between the logic and the presentation in your components.

    • You can test custom hooks independently, ensuring that the logic works correctly, and then focus on testing the components that use these hooks.

  5. Consistent Naming Convention:

    • Custom hooks follow a naming convention by starting with the word "use" (e.g., useEffect, useReducer).

    • This convention helps developers easily recognize and understand that a particular function is a hook and should be used with the rules of hooks in mind.


Implementation of Custom Hook

To under stand custom hook we will be making a custom hook which will return mouse positions in an object form.

Step 1: Create a file with name useMousePosition.js in the path /src/utils

Step 2: Importing the necessary hook which are needed for our custom hook

Step 3: Exporting a function name useMousePosition

Step 4: Creating a state variable for storing our mouse position and giving a default value of an Object .

{ x: 0, y: 0 }

Step 5: Add an Event Listener on our window which will be listening to a mosemove event and will be calling function namely updateMousePosition . And to call it when our page renders we will be wrapping it with useEffect Hook .

Step 6: Creating updateMousePosition() which will change the value of our mousePosition State when called.

Step 7: Creating a cleanup function to remove the mouse Event Listener on window everytime when the use of Event Listener is over.

Step 8: Now we will return the newly updated value

Step 9: Now to make use of this hook we will import this hook in our App.jsx and use this hook

Step 10: Final Output!!!

As you can see when we hover our cursor on the window, the Cursor/Mouse Positions are logged on our console.


So, in this blog, we learned about Custom Hook in ReactJS, When to use CustomHook, Why to use Custom Hook and The implementation of Custom Hook . There is much more to learn about Custom Hook in ReactJS, explore this topic and its used cases and elevate your skills.

Adios Amigos 👋👋

Did you find this article valuable?

Support Coding Adda by becoming a sponsor. Any amount is appreciated!

Â