8000 useMountedOnce · GitHub
[go: up one dir, main page]

Skip to content

Instantly share code, notes, and snippets.

@pavankumar-patruni
Created December 4, 2024 09:41
Show Gist options
  • Save pavankumar-patruni/5a6e51556b0cd0852e86650296a063c8 to your computer and use it in GitHub Desktop.
Save pavankumar-patruni/5a6e51556b0cd0852e86650296a063c8 to your computer and use it in GitHub Desktop.
useMountedOnce

useMountedOnce

useMountedOnce is a custom React hook that allows you to run a callback function only once when the component is mounted. This hook ensures that the callback is executed only during the component's first render and is not triggered on subsequent re-renders. It’s useful when you need to perform an action (e.g., data fetching, subscriptions) just once after the component has mounted, without triggering it on every render.

Usage

Here’s how you can use the useApiService hook in your React component:

useMountedOnce(() => {
    const socket = new WebSocket('wss://example.com/socket');
    
    socket.onopen = () => {
      console.log('WebSocket connected!');
    };

    socket.onmessage = (event) => {
      console.log('Received message:', event.data);
    };

    // Cleanup function to close WebSocket connection when the component unmounts
    return () => {
      socket.close();
      console.log('WebSocket connection closed.');
    };
  });

Parameters

callback: The callback function that you want to execute once after the component has mounted.

useEffect vs useMountedOnce

Feature useEffect useMountedOnce
Runs After every render (unless dependency array is provided) Only once after the initial render
Dependencies Supports dependencies to trigger effect re-run No need for dependencies (always runs once)
Cleanup Supports cleanup for side effects Optionally supports cleanup inside the callback
State & Props Updates Re-runs on state/prop changes (if dependencies change) Does not re-run on state/prop updates
Use Case General side effects (data fetching, DOM manipulation, etc.) Actions that should only happen once on mount (e.g., initialization, analytics tracking)
import { useEffect, useRef } from "react";
const useMountedOnce = (callback: () => void) => {
const mountedOnceRef = useRef(false);
useEffect(() => {
if (!mountedOnceRef.current) {
mountedOnceRef.current = true;
callback();
}
}, [callback]);
};
export default useMountedOnce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
0