DEV Community

Cover image for React Custom Hook: useEffectOnce
Sergey Leschev
Sergey Leschev

Posted on

React Custom Hook: useEffectOnce

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useEffectOnce" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks

import { useEffect } from "react"

export default function useEffectOnce(cb) {
    useEffect(cb, [])
}
Enter fullscreen mode Exit fullscreen mode

The useEffectOnce hook is designed to streamline the process of running effects only once when a component mounts. With just a few lines of code, you can eliminate the need to manually specify an empty dependency array ([]). Here's how it works:

By encapsulating the repetitive useEffect pattern, useEffectOnce allows you to focus on the logic within the effect function itself. This elegant solution saves you from writing boilerplate code repeatedly and helps keep your component files clean and concise.

To showcase the power of useEffectOnce, let's consider a practical example:

import { useState } from "react"
import useEffectOnce from "./useEffectOnce"

export default function EffectOnceComponent() {
    const [count, setCount] = useState(0)
    useEffectOnce(() => alert("Hi"))
    return (
        <>
            <div>{count}</div>
            <button onClick={() => setCount(c => c + 1)}>Increment</button>
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

In this case, when EffectOnceComponent mounts, the useEffectOnce hook triggers the alert "Hi" exactly once. It frees you from manually managing the effect dependencies and ensures your effect runs efficiently.

This custom hook is incredibly versatile and can be utilized in various scenarios. Whether you need to fetch initial data, set up event listeners, or initialize third-party libraries, useEffectOnce simplifies the process and promotes cleaner code organization.

Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4

Top comments (0)