React & React NativeHooksFollowsuseUnfollowUserByUserId

useUnfollowUserByUserId

Overview

The useUnfollowUserByUserId hook allows the current logged-in user to unfollow another user using their user ID. This is the most straightforward way to unfollow someone when you know their user ID.

Usage Example

import { useUnfollowUserByUserId } from "@replyke/react-js";
 
function UnfollowButton({ targetUserId }: { targetUserId: string }) {
  const unfollowUserByUserId = useUnfollowUserByUserId();
 
  const handleUnfollow = async () => {
    try {
      await unfollowUserByUserId({ userId: targetUserId });
      console.log("Successfully unfollowed the user.");
    } catch (error) {
      console.error("Failed to unfollow user:", error.message);
    }
  };
 
  return <button onClick={handleUnfollow}>Unfollow</button>;
}

Advanced Usage with Loading State

import { useUnfollowUserByUserId } from "@replyke/react-js";
import { useState } from "react";
 
function UnfollowButton({
  userId,
  username,
  onUnfollowSuccess
}: {
  userId: string;
  username: string;
  onUnfollowSuccess?: () => void;
}) {
  const unfollowUserByUserId = useUnfollowUserByUserId();
  const [isUnfollowing, setIsUnfollowing] = useState(false);
 
  const handleUnfollow = async () => {
    setIsUnfollowing(true);
    try {
      await unfollowUserByUserId({ userId });
      console.log(`Successfully unfollowed ${username}`);
      onUnfollowSuccess?.();
    } catch (error) {
      console.error(`Failed to unfollow ${username}:`, error);
      alert("Failed to unfollow. Please try again.");
    } finally {
      setIsUnfollowing(false);
    }
  };
 
  return (
    <button
      onClick={handleUnfollow}
      disabled={isUnfollowing}
      className={`unfollow-btn ${isUnfollowing ? 'loading' : ''}`}
    >
      {isUnfollowing ? "Unfollowing..." : "Unfollow"}
    </button>
  );
}

Usage in User Profile

import { useUnfollowUserByUserId } from "@replyke/react-js";
import { useState } from "react";
 
function UserProfileActions({
  user,
  isFollowing,
  onFollowStatusChange
}: {
  user: { id: string; username: string };
  isFollowing: boolean;
  onFollowStatusChange: (isFollowing: boolean) => void;
}) {
  const unfollowUserByUserId = useUnfollowUserByUserId();
  const [isProcessing, setIsProcessing] = useState(false);
 
  const handleUnfollow = async () => {
    if (!isFollowing) return;
 
    const confirmed = window.confirm(
      `Are you sure you want to unfollow ${user.username}?`
    );
    if (!confirmed) return;
 
    setIsProcessing(true);
    try {
      await unfollowUserByUserId({ userId: user.id });
      onFollowStatusChange(false);
      console.log(`Unfollowed ${user.username}`);
    } catch (error) {
      console.error("Failed to unfollow:", error);
      alert("Failed to unfollow user. Please try again.");
    } finally {
      setIsProcessing(false);
    }
  };
 
  if (!isFollowing) return null;
 
  return (
    <div className="profile-actions">
      <button
        onClick={handleUnfollow}
        disabled={isProcessing}
        className="unfollow-btn"
      >
        {isProcessing ? "Processing..." : "Unfollow"}
      </button>
    </div>
  );
}

Bulk Unfollow Usage

import { useUnfollowUserByUserId } from "@replyke/react-js";
import { useState } from "react";
 
function BulkUnfollowManager({ userIds }: { userIds: string[] }) {
  const unfollowUserByUserId = useUnfollowUserByUserId();
  const [isProcessing, setIsProcessing] = useState(false);
  const [processedCount, setProcessedCount] = useState(0);
 
  const handleBulkUnfollow = async () => {
    setIsProcessing(true);
    setProcessedCount(0);
 
    for (let i = 0; i < userIds.length; i++) {
      try {
        await unfollowUserByUserId({ userId: userIds[i] });
        setProcessedCount(i + 1);
        // Add delay to avoid rate limiting
        if (i < userIds.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      } catch (error) {
        console.error(`Failed to unfollow user ${userIds[i]}:`, error);
      }
    }
 
    setIsProcessing(false);
    console.log(`Bulk unfollow completed. Processed ${processedCount} users.`);
  };
 
  return (
    <div>
      <button
        onClick={handleBulkUnfollow}
        disabled={isProcessing}
      >
        {isProcessing
          ? `Unfollowing... ${processedCount}/${userIds.length}`
          : `Unfollow ${userIds.length} Users`
        }
      </button>
    </div>
  );
}

Parameters & Returns

Parameters

The hook returns a function that accepts an object with the following field:

ParameterTypeRequiredDescription
userIdstringYesThe ID of the user to unfollow

Returns

The function does not return a value but ensures the unfollow action is executed successfully on the server.

Error Handling

The hook will throw errors in the following cases:

  • No project is specified
  • No user is logged in
  • No user ID is provided
  • Attempting to unfollow yourself

Use Cases

This hook is commonly used when:

  • Building unfollow buttons in user profiles
  • Managing following lists with user-centric actions
  • Implementing social features in user interfaces
  • Creating bulk unfollow functionality
  • Building follow/unfollow toggle components
  • useUnfollowByFollowId - Unfollow using follow relationship ID
  • useFollowUser - Follow a user
  • useFetchFollowStatus - Check if you’re following a user
  • useFollowManager - Comprehensive follow state management