DEV Community

Cover image for React Custom Hooks (useEventListener)
sundarbadagala
sundarbadagala

Posted on

1

React Custom Hooks (useEventListener)

INTRO πŸ””

Hello World! πŸ‘‹
Now we are discussing another beautiful hook, that is useEventListenerπŸ”₯.

USAGE πŸ””

Sometimes we need to use Event ListenersπŸš€ (JavaScript Event Listeners) in React AppsπŸ’». Every time while use event listeners we need to call them and remove them after the call. React custom hook concept will help us to make these listeners readable and efficient😎.

CODE πŸ””

import { useEffect } from "react";

export const useEventListener = (callback, event, element = "window") => {
  useEffect(() => {
    if (element === "window" && typeof window !== undefined) {
      window.addEventListener(event, callback);
    } else {
      const tagEl = document.getElementById(element);
      tagEl.addEventListener(event, callback);
    }
    return () => window.removeEventListener(event, callback);
  }, []);
};
Enter fullscreen mode Exit fullscreen mode

USE CASE πŸ””

WITHOUT HOOK πŸ”‡

import React, { useEffect } from "react";

function Index() {
  const callback = (type) => {
    console.log(type);
  };
  useEffect(() => {
    const contEl = document.getElementById("container");
    contEl.addEventListener("mouseover", () => callback("over"));
    contEl.addEventListener("mouseout", () => callback("out"));

    return () => {
      contEl.removeEventListener("mouseover", callback);
      contEl.removeEventListener("mouseout", callback);
    };
  }, []);
  return (
    <div>
      <div
        id="container"
        style={{ width: "100px", height: "100px", background: "red" }}
      >
        Hello World
      </div>
    </div>
  );
}

export default Index;
Enter fullscreen mode Exit fullscreen mode

WITH HOOK πŸ”Š

import React from "react";
import { useEventListener } from "./hook";

function Index() {
  const callback = (type) => {
    console.log(type);
  };
  useEventListener(() => callback("over"), "mouseover", "container");
  useEventListener(() => callback("out"), "mouseout", "container");
  return (
    <div>
      <div
        id="container"
        style={{ width: "100px", height: "100px", background: "red" }}
      >
        Hello World
      </div>
    </div>
  );
}

export default Index;
Enter fullscreen mode Exit fullscreen mode

SOME OTHER EXAMPLES

import React from "react";
import { useEventListener } from "./hook";

function Index() {
  useEventListener(() => {
    console.log("scrolling...");
  }, "scroll");
  return (
    <div>
      <div
        id="container"
        style={{ width: "100px", height: "1000px", background: "red" }}
      >
        Hello World
      </div>
    </div>
  );
}

export default Index;
Enter fullscreen mode Exit fullscreen mode
import React from "react";
import { useEventListener } from "./hook";

function Index() {
  useEventListener(() => {
      console.log("clicked...");
    },
    "click", "btn");
  return (
    <div>
      <button id="btn">click here</button>
    </div>
  );
}

export default Index;
Enter fullscreen mode Exit fullscreen mode

CONCLUSION πŸ””

This is a very helpful hook to call event listeners in React Apps.
I hope this hook is very helpful. We will discuss another new hook in our next post.

Peace πŸ™‚

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay